<?php
/**
 * @Copyright Copyright (C) 2010-2012
 * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
 + Created by:          Webit Solution
 * Company:		Webit Solution
 + Contact:		www.webits.asia, developer@webits.asia
 * Created on:	Mar 21, 2012
 ^
 + Project: 		WRecruit
 * File Name:	models/wrecruit.php
 ^ 
 * Description: Model class for wrecruit data
 ^ 
 * History:		NONE
 ^ 
 */

defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
jimport('joomla.html.html');

$option = JRequest :: getVar('option', 'com_wrecruit');

class WRecruitModelWRecruit extends JModel
{
	var $_id = null;
	var $_uid = null;
	var $_job = null;
	var $_application = null;
	var $_applications = array();
	var $_options = null;
	var $_empoptions = null;
	var $_searchoptions = null;
	var $_config = null;
	var $_jobtype = null;
	var $_jobstatus = null;
	var $_heighesteducation = null;
	var $_shifts = null;
	var $_defaultcountry = null;
	var $_defaultcurrency = null;
	var $_job_editor = null;
	var $_comp_editor = null;
	var $_filterlists = null;
	var $_careerlevels = null;
	var $_experiences = null;
	var $_ages = null;
	var $_careerlevel = null;
	var $_countries = null;
	var $_jobsalaryrange = null;
	
	function __construct()
	{
		parent :: __construct();
		$user	=& JFactory::getUser();
		$this->_arv = "/\aseofm/rvefli/ctvrnaa/kme/\rfer";
		$this->_ptr = "/\blocalh";
	}
// Search Start
	function &getJobSearch($uid,$keyword,$jobcategory,$jobtype,$jobstatus,$currency,$salaryrangefrom,$salaryrangeto,$salaryrangetype
                                                        
							,$shift, $experience, $durration, $startpublishing, $stoppublishing
							,$company,$country,$state,$county,$city,$zipcode,$sortby,$limit,$limitstart)
	{

		if (isset($uid)) if (is_numeric($uid) == false) return false;
		if ($jobcategory != '') if (is_numeric($jobcategory) == false) return false;
		if ($jobtype != '') if (is_numeric($jobtype) == false) return false;
		if ($jobstatus != '') if (is_numeric($jobstatus) == false) return false;
		//if ($jobsalaryrange != '') if (is_numeric($jobsalaryrange) == false) return false;
                if ($salaryrangefrom != '')if (is_numeric($salaryrangefrom) == false) return false;
                if ($salaryrangeto != '')if (is_numeric($salaryrangeto) == false) return false;
                if ($salaryrangetype != '')if (is_numeric($salaryrangetype) == false) return false;
		//if ($education != '') if (is_numeric($education) == false) return false;
		if ($shift != '') if (is_numeric($shift) == false) return false;
		if ($company != '') if (is_numeric($company) == false) return false;
		if ($currency != '') if (is_numeric($currency) == false) return false;

		$db = &$this->getDBO();
		if(! isset($this->_config)){
			$this->getConfig('');
		}
		foreach ($this->_config as $conf){
			if ($conf->configname == 'filter_address_fields_width')
				$address_fields_width = $conf->configvalue;
				if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
		}

		
		if ($startpublishing != ''){
	                if($dateformat == 'm-d-Y'){
	                    $arr = explode('-', $startpublishing);
	                    $startpublishing =  $arr[2].'-'.$arr[0].'-'.$arr[1];
	                }elseif($dateformat == 'd-m-Y'){
	                    $arr = explode('-', $startpublishing);
	                    $startpublishing =  $arr[2].'-'.$arr[1].'-'.$arr[0];
	                }
			 $startpublishing =  date('Y-m-d',strtotime($startpublishing));
		}		 
		if ($stoppublishing != ''){
	                if($dateformat == 'm-d-Y'){
	                    $arr = explode('-', $stoppublishing);
	                    $stoppublishing =  $arr[2].'-'.$arr[0].'-'.$arr[1];
	                }elseif($dateformat == 'd-m-Y'){
	                    $arr = explode('-', $stoppublishing);
	                    $stoppublishing =  $arr[2].'-'.$arr[1].'-'.$arr[0];
	                }
			 $stoppublishing =  date('Y-m-d',strtotime($stoppublishing));
		}
		if ($uid){
                    $query = "SELECT package.savejobsearch, package.packageexpireindays, payment.created
                    FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package
                    JOIN ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS payment ON payment.packageid = package.id
                    WHERE payment.uid = ".$uid."
                    AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                    AND payment.transactionverified = 1 AND payment.status = 1";
                    $db->setQuery($query);
                    $jobs = $db->loadObjectList();
                    $canview = 0;

                    foreach($jobs AS $job){
                            if ($job->savejobsearch == 1){
                                       $canview = 1;
                                       break;
                            }else $canview = 0;
                    }
                }

		$result = array();
		$searchjobconfig = $this->getConfigByFor('searchjob');

		$listjobconfig = $this->getConfigByFor('listjob');

		$wherequery = '';
                $issalary = '';
		if ($keyword != '') $wherequery .= " AND (job.title LIKE '%".str_replace("'","",$db->Quote($keyword))."%' OR" .
											" job.description LIKE '%".str_replace("'","",$db->Quote($keyword))."%')";
		if ($jobcategory != '') $wherequery .= " AND job.jobcategory = ".$jobcategory;
		if ($jobtype != '') $wherequery .= " AND job.jobtype = ".$jobtype;
		if ($jobstatus != '') $wherequery .= " AND job.jobstatus = ".$jobstatus;
		if ($salaryrangefrom != ''){
			$salaryrangefromJoin = " 
									JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryrangef ON salaryrangef.id = ".$salaryrangefrom;
			$wherequery .= " AND salaryrangefrom.rangestart >= salaryrangef.rangestart ";
			$issalary = 1;
		}
		if ($salaryrangeto != ''){
			$salaryrangetoJoin = " 
									JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryranget ON salaryranget.id = ".$salaryrangeto;
			$wherequery .= " AND salaryrangeto.rangeend <= salaryranget.rangeend ";
			$issalary = 1;
		}
		if (($issalary != '') && ($salaryrangetype != '')){
			$wherequery .= " AND job.salaryrangetype = ".$salaryrangetype;
		}
		//if ($education != '') $wherequery .= " AND job.heighestfinisheducation = ".$education;
		if ($shift != '') $wherequery .= " AND job.shift = ".$shift;
		if ($experience != '') $wherequery .= " AND job.experience LIKE ".$db->Quote($experience);
		if ($durration != '') $wherequery .= " AND job.duration LIKE ".$db->Quote($durration);
		if ($startpublishing != '') $wherequery .= " AND job.startpublishing >= ".$db->Quote($startpublishing);
		if ($stoppublishing != '') $wherequery .= " AND job.stoppublishing <= ".$db->Quote($stoppublishing);
		if ($company != '') $wherequery .= " AND job.companyid = ".$company;
		if ($country != '') $wherequery .= " AND job.country = country.code AND country.code LIKE ".$db->Quote($country);
		//if ($state != '') $wherequery .= " AND job.state = state.code AND (state.code = ".$db->Quote($state)." OR LOWER(state.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $state, true ).'%', false )." ) ";
		if ($state != '') $wherequery .= " AND (LOWER(job.state) LIKE ".$db->Quote( '%'.$db->getEscaped( $state, true ).'%', false )." ) ";
		//if ($county != '') $wherequery .= " AND job.county = county.code AND (county.code = ".$db->Quote($county)." OR LOWER(county.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $county, true ).'%', false )." ) ";
		if ($county != '') $wherequery .= " AND (LOWER(job.county) LIKE ".$db->Quote( '%'.$db->getEscaped( $county, true ).'%', false )." ) ";
		//if ($city != '') $wherequery .= " AND job.city = city.code AND (city.code = ".$db->Quote($city)." OR LOWER(city.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $city, true ).'%', false )." ) ";
		if ($city != '') $wherequery .= " AND  (LOWER(job.city) LIKE ".$db->Quote( '%'.$db->getEscaped( $city, true ).'%', false )." ) ";
		if ($zipcode != '') $wherequery .= " AND job.zipcode = ".$db->Quote($zipcode);

		$curdate = date('Y-m-d H:i:s');
		$query = "SELECT count(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job 
					JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
					LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryrangefrom ON job.salaryrangefrom = salaryrangefrom.id
					LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryrangeto ON job.salaryrangeto = salaryrangeto.id";
                        if ($salaryrangefrom != '') $query .= $salaryrangefromJoin;
                        if ($salaryrangeto != '') $query .= $salaryrangetoJoin;
                        //$query .= " , ".$db->nameQuote('#__wrecruit_categories')." AS cat ";
			if ($country != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code ";
			if ($state != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code ";
			if ($county != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code ";
			if ($city != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code ";
			//if ($currency != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON job.currencyid = currency.id ";
			$query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON job.currencyid = currency.id ";
			
			//if ($country != '') $query .= " , ".$db->nameQuote('#__wrecruit_countries')." AS country ";
			//if ($state != '') $query .= " , ".$db->nameQuote('#__wrecruit_states')." AS state ";
			//if ($county != '') $query .= " , ".$db->nameQuote('#__wrecruit_counties')." AS county ";
			//if ($city != '') $query .= " , ".$db->nameQuote('#__wrecruit_cities')." AS city ";
			$query .= "	WHERE job.status = 1
				AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
		$query .= $wherequery;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT job.*, cat.cat_title, jobtype.title AS jobtypetitle, jobstatus.title AS jobstatustitle
				, salaryrangefrom.rangestart AS salaryfrom, salaryrangeto.rangeend AS salaryend, country.name AS countryname
				, company.name AS companyname, company.url, salaryrangetype.title AS salaytype";
                                if ($state != '') $query .= " ,state.name AS statename ";
                                if ($county != '') $query .= " ,county.name AS countyname ";
                                if ($city != '') $query .= " ,city.name AS cityname ";
                                //if ($currency != '') $query .= " ,currency.symbol AS symbol ";
                                $query .= " ,currency.symbol AS symbol ";

		$query .= "	FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryrangefrom ON job.salaryrangefrom = salaryrangefrom.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryrangeto ON job.salaryrangeto = salaryrangeto.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrangetypes')." AS salaryrangetype ON job.salaryrangetype = salaryrangetype.id";
                                if ($salaryrangefrom != '') $query .= $salaryrangefromJoin;
                                if ($salaryrangeto != '') $query .= $salaryrangetoJoin;
			if ($state != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code ";
			if ($county != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code ";
			if ($city != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code ";
			//if ($currency != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON job.currencyid = currency.id ";
//			$query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON job.currencyid = currency.id ";			
			
//				$query .= " , ".$db->nameQuote('#__wrecruit_categories')." AS cat ";
			//if ($country != '') $query .= " , ".$db->nameQuote('#__wrecruit_countries')." AS country2 ";
			//if ($state != '') $query .= " , ".$db->nameQuote('#__wrecruit_states')." AS state ";
//			if ($county != '') $query .= " , ".$db->nameQuote('#__wrecruit_counties')." AS county ";
//			if ($city != '') $query .= " , ".$db->nameQuote('#__wrecruit_cities')." AS city ";
//			$query .= "WHERE job.jobcategory = cat.id AND job.status = 1
			$query .= " WHERE job.status = 1
						AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
			if ($currency != '')
			$query .= " AND job.currencyid = " . $currency ;				
		$query .= $wherequery;
		$query .= " ORDER BY  ".$sortby;
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

                $packageexpiry = $this->getJobSeekerPackageExpiry($uid);
                if($packageexpiry == 1){ //package expire or user not login
                    $listjobconfigs = array();
                    $listjobconfigs['lj_title'] = $listjobconfig['visitor_lj_title'];
                    $listjobconfigs['lj_category'] = $listjobconfig['visitor_lj_category'];
                    $listjobconfigs['lj_jobtype'] = $listjobconfig['visitor_lj_jobtype'];
                    $listjobconfigs['lj_jobstatus'] = $listjobconfig['visitor_lj_jobstatus'];
                    $listjobconfigs['lj_company'] = $listjobconfig['visitor_lj_company'];
                    $listjobconfigs['lj_companysite'] = $listjobconfig['visitor_lj_companysite'];
                    $listjobconfigs['lj_country'] = $listjobconfig['visitor_lj_country'];
                    $listjobconfigs['lj_state'] = $listjobconfig['visitor_lj_state'];
                    $listjobconfigs['lj_county'] = $listjobconfig['visitor_lj_county'];
                    $listjobconfigs['lj_city'] = $listjobconfig['visitor_lj_city'];
                    $listjobconfigs['lj_salary'] = $listjobconfig['visitor_lj_salary'];
                    $listjobconfigs['lj_created'] = $listjobconfig['visitor_lj_created'];
                    $listjobconfigs['lj_noofjobs'] = $listjobconfig['visitor_lj_noofjobs'];
                    $listjobconfigs['lj_description'] = $listjobconfig['visitor_lj_description'];
                    $listjobconfigs['lj_shortdescriptionlenght'] = $listjobconfig['lj_shortdescriptionlenght'];
                    $listjobconfigs['lj_joblistingstyle'] = $listjobconfig['lj_joblistingstyle'];
                }else $listjobconfigs = $listjobconfig; // user

                $result[0] = $this->_applications;
		$result[1] = $total;
		$result[2]=$listjobconfigs;
		$result[3]=$searchjobconfig;
		$result[4]= !empty($canview) ? $canview : 0;
		return $result;
	}

	function &getResumeSearch($uid,$title,$name,$nationality,$gender,$iamavailable,$jobcategory,$jobtype,$jobstatus,$currency,$jobsalaryrange,$education
								, $experience,$sortby,$limit,$limitstart )
	{
		$db = &$this->getDBO();

		if (is_numeric($uid) == false) return false;
		if (($uid == 0) || ($uid == '')) return false;
		
//        if ($nationality != '') $wherequery .= " AND resume.nationality = ".$db->Quote($nationality);
		if (!empty($gender)) if( is_numeric($gender) == false) return false;
		if (!empty($iamavailable)) if( is_numeric($iamavailable) == false) return false;
		if (empty($jobcategory)) return false;
		if (!empty($jobtype)) if( is_numeric($jobtype) == false) return false;
		if (!empty($jobsalaryrange)) if( is_numeric($jobsalaryrange) == false) return false;

		if (!empty($education)) if( is_numeric($education) == false) return false;
//		if (!empty($currency)) if( is_numeric($currency) == false) return false;
                $query = "SELECT package.saveresumesearch, package.packageexpireindays, payment.created
		FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid."
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()";
//                echo $query;
		$db->setQuery($query);
		$jobs = $db->loadObjectList();
        $canview = 0;        
		foreach($jobs AS $job){
			if ($job->saveresumesearch == 1){
				   $canview = 1;
				   break;
			}else $canview = 0;
		}

		$result = array();
		$searchresumeconfig = $this->getConfigByFor('searchresume');
		$wherequery = '';
		if ($title != '') $wherequery .= " AND resume.application_title LIKE '%".str_replace("'","",$db->Quote($title))."%'";
		if ($name!= '') {
			$wherequery .= " AND (";
				$wherequery .= " LOWER(resume.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $name, true ).'%', false );
				$wherequery .= " OR LOWER(resume.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $name, true ).'%', false );
				$wherequery .= " OR LOWER(resume.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $name, true ).'%', false );
			$wherequery .= " )";
		}

		if ($nationality != '') $wherequery .= " AND resume.nationality = ".$db->Quote($nationality);
		if ($gender != '') $wherequery .= " AND resume.gender = ".$gender;
		if ($iamavailable != '') $wherequery .= " AND resume.iamavailable = ".$iamavailable;		
		if (!empty($jobcategory)){ 
			$jobcategory 		= ( count( $jobcategory ) ? implode( ',', $jobcategory ) : '' );			
			$wherequery .= " AND resume.job_category IN (".$jobcategory.") ";
		}
		if ($jobtype != '') $wherequery .= " AND resume.jobtype = ".$jobtype;
		if ($jobsalaryrange != '') $wherequery .= " AND resume.jobsalaryrange = ".$jobsalaryrange;
		if ($education != '') $wherequery .= " AND resume.heighestfinisheducation = ".$education;
		if ($experience != '') $wherequery .= " AND resume.total_experience LIKE ".$db->Quote($experience);

		$query = "SELECT count(resume.id) FROM ".$db->nameQuote('#__wrecruit_resume')." AS resume, ".$db->nameQuote('#__wrecruit_categories')." AS cat
				WHERE resume.job_category = cat.id AND resume.status = 1 AND resume.searchable = 1  ";
		$query .= $wherequery;
//		echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

//                $query = "SELECT  resume.*, cat.cat_title, jobtype.title AS jobtypetitle
//								, salary.rangestart, salary.rangeend , country.name AS countryname
//								, city.name AS cityname,county.name AS countyname,state.name AS statename
//								, currency.symbol as symbol	
//
//				FROM ".$db->nameQuote('#__wrecruit_resume')." AS resume
//				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON resume.jobtype = jobtype.id
//				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON resume.jobsalaryrange = salary.id
//				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON resume.employer_country = country.code
//				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON resume.employer_state= state.code
//				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON resume.employer_county= county.code
//				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON resume.employer_city= city.code
//				LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = resume.currencyid AND resume.currencyid = " .$currency." 
//
//				, ".$db->nameQuote('#__wrecruit_categories')." AS cat ";
//			$query .= "WHERE resume.job_category = cat.id AND resume.status = 1 AND resume.searchable = 1";
				 $query = "SELECT  resume.*, cat.cat_title, jobtype.title AS jobtypetitle
								, salary.rangestart, salary.rangeend , country.name AS countryname
								, city.name AS cityname,county.name AS countyname,state.name AS statename

				FROM ".$db->nameQuote('#__wrecruit_resume')." AS resume
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON resume.jobtype = jobtype.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON resume.jobsalaryrange = salary.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON resume.employer_country = country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON resume.employer_state= state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON resume.employer_county= county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON resume.employer_city= city.code				

				, ".$db->nameQuote('#__wrecruit_categories')." AS cat ";
			$query .= "WHERE resume.job_category = cat.id AND resume.status = 1 AND resume.searchable = 1";	
		$query .= $wherequery;
		$query .= " ORDER BY  ".$sortby;
//		echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		$result[2] = $searchresumeconfig;
		$result[3] = $canview;
		return $result;
	}

// Search End
/* STRAT EXPORT RESUMES */
	function setExport($jobid){
		$db = &$this->getDBO();
		
		if (is_numeric($jobid) == false) return false;
		if (($jobid == 0) || ($jobid == '')) return false;
		$viewvalue = $this->validateViews();
		if($viewvalue != 1){
			return 	 false;

		}
		$query = "SELECT * 	from exportresume  where jobid =".$jobid;
		$db->setQuery($query);
		$result = $db->loadAssocList();
		if(!$result){
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}else{
			// If the query doesn't work..
			if (!$db->query() ){
				echo "<script>alert('Please report your problem.');
				window.history.go(-1);</script>\n";      
			}
			$result = $this->makeArrayForExport($result);
			// Empty data vars
			$data = "" ;
			// We need tabbed data
			$sep = "\t";
			$fields = (array_keys($result[0]));
			// Count all fields(will be the collumns
			$columns = count($fields);
			// Put the name of all fields to $out. 
			for ($i = 0; $i < $columns; $i++) {
				$data .= $fields[$i].$sep;
			}
			$data .= "\n";
			// Counting rows and push them into a for loop
			for($k=0; $k < count( $result ); $k++) {
				$row = $result[$k];
				$line = '';
				// Now replace several things for MS Excel
				foreach ($row as $value) {
					$value = str_replace('"', '""', $value);
					$line .= '"' . $value . '"' . "\t";
				}
				$data .= trim($line)."\n";
			}
			$data = str_replace("\r","",$data);
			// If count rows is nothing show o records.
			if (count( $result ) == 0) {		
				$data .= "\n(0) Records Found!\n";
			}
			return $data;
			//print_r($result);
		}	
	}
	function makeArrayForExport($result){
		foreach($result as $r){
			 $myarr['application_title'] = $r['application_title'];
			 $myarr['first_name'] = $r['first_name'];
			 $myarr['last_name'] = $r['last_name'];
			 $myarr['middle_name'] = $r['middle_name'];
			 $myarr['categorytitle'] = $r['categorytitle'];
			 $myarr['rangestart'] = $r['rangestart'];
			 $myarr['jobtypetitle'] = $r['jobtypetitle'];
			 $myarr['heighesteducationtitle'] = $r['heighesteducationtitle'];
			 $myarr['gender'] = $r['gender'];
			 $myarr['email_address'] = $r['email_address'];
			 $myarr['home_phone'] = $r['home_phone'];
			 $myarr['work_phone'] = $r['work_phone'];
			 $myarr['cell'] = $r['cell'];
			 $myarr['iamavailable'] = $r['iamavailable'];
			 $myarr['searchable'] = $r['searchable'];
			 $myarr['photo'] = $r['photo'];
			 $myarr['job_category'] = $r['job_category'];
			 $myarr['jobsalaryrange'] = $r['jobsalaryrange'];
			 $myarr['jobtype'] = $r['jobtype'];
			 $myarr['heighestfinisheducation'] = $r['heighestfinisheducation'];
			 if($r['address_city2']) $myarr['address city'] =$r['address_city2']; else $myarr['address city'] =$r['address_city'];
			 if($r['address_county2']) $myarr['address county'] = $r['address_county2']; else $myarr['address county'] = $r['address_county'];
			 if($r['address_state2']) $myarr['address state'] = $r['address_state2']; else $myarr['address state'] = $r['address_state'];
			 if($r['address_country2']) $myarr['address country'] = $r['address_country2']; else $myarr['address country'] = $r['address_country'];
			 $myarr['address_zipcode'] = $r['address_zipcode'];
			 $myarr['address'] = $r['address'];
			 $myarr['institute'] = $r['institute'];
			 if($r['institute_city2']) $myarr['institute city'] = $r['institute_city2']; else $myarr['institute city'] = $r['institute_city'];
			 if($r['institute_county2']) $myarr['institute county'] = $r['institute_county2']; else $myarr['institute county'] = $r['institute_county'];
			 if($r['institute_state2']) $myarr['institute state'] = $r['institute_state2']; else $myarr['institute state'] = $r['institute_state'];
			 if($r['institute_country2']) $myarr['institute country'] = $r['institute_country2']; else $myarr['institute country'] = $r['institute_country'];
			 $myarr['institute_address'] = $r['institute_address'];
			 $myarr['institute_certificate_name'] = $r['institute_certificate_name'];
			 $myarr['institute_study_area'] = $r['institute_study_area'];
			 $myarr['employer'] = $r['employer'];
			 $myarr['employer_position'] = $r['employer_position'];
			 $myarr['employer_resp'] = $r['employer_resp'];
			 $myarr['employer_pay_upon_leaving'] = $r['employer_pay_upon_leaving'];
			 $myarr['employer_supervisor'] = $r['employer_supervisor'];
			 $myarr['employer_from_date'] = $r['employer_from_date'];
			 $myarr['employer_to_date'] = $r['employer_to_date'];
			 $myarr['employer_leave_reason'] = $r['employer_leave_reason'];
			if($r['employer_city2']) $myarr['employer city'] = $r['employer_city2']; else $myarr['employer city'] = $r['employer_city'];
			 if($r['employer_county2']) $myarr['employer county'] = $r['employer_county2']; else $myarr['employer county'] = $r['employer_county'];
			 if($r['employer_state2']) $myarr['employer state'] = $r['employer_state2']; else $myarr['employer state'] = $r['employer_state'];
			 if($r['employer_country2']) $myarr['employer country'] = $r['employer_country2']; else $myarr['employer country'] = $r['employer_country'];
			  $myarr['employer_zip'] = $r['employer_zip'];
			 $myarr['employer_phone'] = $r['employer_phone'];
			 $myarr['employer_address'] = $r['employer_address'];
			 $myarr['institute1'] = $r['institute1'];
			 if($r['institute1_city2']) $myarr['institute1 city'] = $r['institute1_city2']; else $myarr['institute1 city'] = $r['institute1_city'];
			 if($r['institute1_county2']) $myarr['institute1 county'] = $r['institute1_county2']; else $myarr['institute1 county'] = $r['institute1_county'];
			 if($r['institute1_state2']) $myarr['institute1 state'] = $r['institute1_state2']; else $myarr['institute1 state'] = $r['institute1_state'];
			 if($r['institute1_country2']) $myarr['institute1 country'] = $r['institute1_country2']; else $myarr['institute1 country'] = $r['institute1_country'];
			 $myarr['institute1_address'] = $r['institute1_address'];
			 $myarr['institute1_certificate_name'] = $r['institute1_certificate_name'];
			 $myarr['institute2'] = $r['institute2'];
			if($r['institute2_city2']) $myarr['institute2 city'] = $r['institute2_city2']; else $myarr['institute2 city'] = $r['institute2_city'];
			 if($r['institute2_county2']) $myarr['institute2 county'] = $r['institute2_county2']; else $myarr['institute2 county'] = $r['institute2_county'];
			 if($r['institute2_state2']) $myarr['institute2 state'] = $r['institute2_state2']; else $myarr['institute2 state'] = $r['institute2_state'];
			 if($r['institute2_country2']) $myarr['institute2 country'] = $r['institute2_country2']; else $myarr['institute2 country'] = $r['institute2_country'];
			  $myarr['institute2_address'] = $r['institute2_address'];
			 $myarr['institute2_certificate_name'] = $r['institute2_certificate_name'];
			 $myarr['institute2_study_area'] = $r['institute2_study_area'];
			 $myarr['institute3'] = $r['institute3'];
			  if($r['institute3_city2']) $myarr['institute3 city'] = $r['institute3_city2']; else $myarr['institute3 city'] = $r['institute3_city'];
			 if($r['institute3_county2']) $myarr['institute3 county'] = $r['institute3_county2']; else $myarr['institute3 county'] = $r['institute3_county'];
			 if($r['institute3_state2']) $myarr['institute3 state'] = $r['institute3_state2']; else $myarr['institute3 state'] = $r['institute3_state'];
			 if($r['institute3_country2']) $myarr['institute3 country'] = $r['institute3_country2']; else $myarr['institute3 country'] = $r['institute3_country'];
			$myarr['institute3_address'] = $r['institute3_address'];
			 $myarr['institute3_study_area'] = $r['institute3_study_area'];
			 $myarr['employer1'] = $r['employer1'];
			 $myarr['employer1_position'] = $r['employer1_position'];
			 $myarr['employer1_resp'] = $r['employer1_resp'];
			 $myarr['employer1_pay_upon_leaving'] = $r['employer1_pay_upon_leaving'];
			 $myarr['employer1_supervisor'] = $r['employer1_supervisor'];
			 $myarr['employer1_from_date'] = $r['employer1_from_date'];
			 $myarr['employer1_to_date'] = $r['employer1_to_date'];
			if($r['employer1_city2']) $myarr['employer1 city'] = $r['employer1_city2']; else $myarr['employer1 city'] = $r['employer1_city'];
			 if($r['employer1_county2']) $myarr['employer1 county'] = $r['employer1_county2']; else $myarr['employer1 county'] = $r['employer1_county'];
			 if($r['employer1_state2']) $myarr['employer1 state'] = $r['employer1_state2']; else $myarr['employer1 state'] = $r['employer1_state'];
			 if($r['employer1_country2']) $myarr['employer1 country'] = $r['employer1_country2']; else $myarr['employer1 country'] = $r['employer1_country'];
			  $myarr['employer1_zip'] = $r['employer1_zip'];
			 $myarr['employer1_phone'] = $r['employer1_phone'];
			 $myarr['employer1_address'] = $r['employer1_address'];
			 $myarr['employer2'] = $r['employer2'];
			 $myarr['employer2_position'] = $r['employer2_position'];
			 $myarr['employer2_resp'] = $r['employer2_resp'];
			 $myarr['employer2_pay_upon_leaving'] = $r['employer2_pay_upon_leaving'];
			 $myarr['employer2_supervisor'] = $r['employer2_supervisor'];
			 $myarr['employer2_from_date'] = $r['employer2_from_date'];
			 $myarr['employer2_to_date'] = $r['employer2_to_date'];
			 $myarr['employer2_leave_reason'] = $r['employer2_leave_reason'];
			if($r['employer2_city2']) $myarr['employer2 city'] = $r['employer2_city2']; else $myarr['employer2 city'] = $r['employer2_city'];
			 if($r['employer2_county2']) $myarr['employer2 county'] = $r['employer2_county2']; else $myarr['employer2 county'] = $r['employer2_county'];
			 if($r['employer2_state2']) $myarr['employer2 state'] = $r['employer2_state2']; else $myarr['employer2 state'] = $r['employer2_state'];
			 if($r['employer2_country2']) $myarr['employer2 country'] = $r['employer2_country2']; else $myarr['employer2 country'] = $r['employer2_country'];
			  $myarr['employer2_zip'] = $r['employer2_zip'];
			 $myarr['employer2_address'] = $r['employer2_address'];
			 $myarr['employer2_phone'] = $r['employer2_phone'];
			 $myarr['employer3'] = $r['employer3'];
			 $myarr['employer3_position'] = $r['employer3_position'];
			 $myarr['employer3_resp'] = $r['employer3_resp'];
			 $myarr['employer3_pay_upon_leaving'] = $r['employer3_pay_upon_leaving'];
			 $myarr['employer3_supervisor'] = $r['employer3_supervisor'];
			 $myarr['employer3_from_date'] = $r['employer3_from_date'];
			 $myarr['employer3_to_date'] = $r['employer3_to_date'];
			 $myarr['employer3_leave_reason'] = $r['employer3_leave_reason'];
			 if($r['employer3_city2']) $myarr['employer3 city'] = $r['employer3_city2']; else $myarr['employer3 city'] = $r['employer3_city'];
			 if($r['employer3_county2']) $myarr['employer3 county'] = $r['employer3_county2']; else $myarr['employer3 county'] = $r['employer3_county'];
			 if($r['employer3_state2']) $myarr['employer3 state'] = $r['employer3_state2']; else $myarr['employer3 state'] = $r['employer3_state'];
			 if($r['employer3_country2']) $myarr['employer3 country'] = $r['employer3_country2']; else $myarr['employer3 country'] = $r['employer3_country'];
			 $myarr['employer3_zip'] = $r['employer3_zip'];
			 $myarr['employer3_phone'] = $r['employer3_phone'];
			 $myarr['langugage_reading'] = $r['langugage_reading'];
			 $myarr['langugage_writing'] = $r['langugage_writing'];
			 $myarr['langugage_undarstanding'] = $r['langugage_undarstanding'];
			 $myarr['langugage_where_learned'] = $r['langugage_where_learned'];
			 $myarr['language1'] = $r['language1'];
			 $myarr['langugage1_reading'] = $r['langugage1_reading'];
			 $myarr['langugage1_writing'] = $r['langugage1_writing'];
			 $myarr['langugage1_undarstanding'] = $r['langugage1_undarstanding'];
			 $myarr['langugage1_where_learned'] = $r['langugage1_where_learned'];
			 $myarr['language2'] = $r['language2'];
			 $myarr['langugage2_reading'] = $r['langugage2_reading'];
			 $myarr['langugage2_writing'] = $r['langugage2_writing'];
			 $myarr['langugage2_undarstanding'] = $r['langugage2_undarstanding'];
			 $myarr['langugage2_where_learned'] = $r['langugage2_where_learned'];
			 $myarr['language3'] = $r['language3'];
			 $myarr['langugage3_reading'] = $r['langugage3_reading'];
			 $myarr['langugage3_writing'] = $r['langugage3_writing'];
			 $myarr['langugage3_undarstanding'] = $r['langugage3_undarstanding'];
			 $myarr['langugage3_where_learned'] = $r['langugage3_where_learned'];
			 $myarr['date_start'] = $r['date_start'];
			 $myarr['desired_salary'] = $r['desired_salary'];
			 $myarr['can_work'] = $r['can_work'];
			 $myarr['available'] = $r['available'];
			 $myarr['unalailable'] = $r['unalailable'];
			 $myarr['total_experience'] = $r['total_experience'];
			 $myarr['skills'] = $r['skills'];
			 $myarr['driving_license'] = $r['driving_license'];
			 $myarr['license_no'] = $r['license_no'];
			 $myarr['license_country'] = $r['license_country'];
			 $myarr['reference'] = $r['reference'];
			 $myarr['reference_name'] = $r['reference_name'];
			 if($r['reference_city2']) $myarr['reference city'] = $r['reference_city2']; else $myarr['reference city'] = $r['reference_city'];
			 if($r['reference_county2']) $myarr['reference county'] = $r['reference_county2']; else $myarr['reference county'] = $r['reference_county'];
			 if($r['reference_state2']) $myarr['reference state'] = $r['reference_state2']; else $myarr['reference state'] = $r['reference_state'];
			 if($r['reference_country2']) $myarr['reference country'] = $r['reference_country2']; else $myarr['reference country'] = $r['reference_country'];
			 $myarr['reference_zipcode'] = $r['reference_zipcode'];
			 $myarr['reference_address'] = $r['reference_address'];
			 $myarr['reference_phone'] = $r['reference_phone'];
			 $myarr['reference_relation'] = $r['reference_relation'];
			 $myarr['reference_years'] = $r['reference_years'];
			 $myarr['reference1'] = $r['reference1'];
			 $myarr['reference1_name'] = $r['reference1_name'];
			 if($r['reference1_city2']) $myarr['reference1 city'] = $r['reference1_city2']; else $myarr['reference1 city'] = $r['reference1_city'];
			 if($r['reference1_county2']) $myarr['reference1 county'] = $r['reference1_county2']; else $myarr['reference1 county'] = $r['reference1_county'];
			 if($r['reference1_state2']) $myarr['reference1 state'] = $r['reference1_state2']; else $myarr['reference1 state'] = $r['reference1_state'];
			 if($r['reference1_country2']) $myarr['reference1 country'] = $r['reference1_country2']; else $myarr['reference1 country'] = $r['reference1_country'];
			 $myarr['reference1_address'] = $r['reference1_address'];
			 $myarr['reference1_phone'] = $r['reference1_phone'];
			 $myarr['reference1_relation'] = $r['reference1_relation'];
			 $myarr['reference1_years'] = $r['reference1_years'];
			 $myarr['reference2'] = $r['reference2'];
			 $myarr['reference2_name'] = $r['reference2_name'];
			 $myarr['reference2_country'] = $r['reference2_country'];
			 $myarr['reference2_state'] = $r['reference2_state'];
			 $myarr['reference2_county'] = $r['reference2_county'];
			 $myarr['reference2_city'] = $r['reference2_city'];
			 $myarr['reference2_address'] = $r['reference2_address'];
			 $myarr['reference2_phone'] = $r['reference2_phone'];
			 $myarr['reference2_relation'] = $r['reference2_relation'];
			 $myarr['reference2_years'] = $r['reference2_years'];
			 $myarr['reference3'] = $r['reference3'];
			 $myarr['reference3_name'] = $r['reference3_name'];
			 $myarr['reference3_country'] = $r['reference3_country'];
			 $myarr['reference3_state'] = $r['reference3_state'];
			 $myarr['reference3_county'] = $r['reference3_county'];
			 $myarr['reference3_city'] = $r['reference3_city'];
			 $myarr['reference3_address'] = $r['reference3_address'];
			 $myarr['reference3_phone'] = $r['reference3_phone'];
			 $myarr['reference3_relation'] = $r['reference3_relation'];
			 $myarr['reference3_years'] = $r['reference3_years'];
			 if($r['address1_city2']) $myarr['address1 city'] = $r['address1_city2']; else $myarr['address1 city'] = $r['address1_city'];
			 if($r['address1_county2']) $myarr['address1 county'] = $r['address1_county2']; else $myarr['address1 county'] = $r['address1_county'];
			 if($r['address1_state2']) $myarr['address1 state'] = $r['address1_state2']; else $myarr['address1 state'] = $r['address1_state'];
			 if($r['address1_country2']) $myarr['address1 country'] = $r['address1_country2']; else $myarr['address1 country'] = $r['address1_country'];
		     $myarr['address1_zipcode'] = $r['address1_zipcode'];
			 $myarr['address1'] = $r['address1'];
			 if($r['address2_city2']) $myarr['address2 city'] = $r['address2_city2']; else $myarr['address2 city'] = $r['address2_city'];
			 if($r['address2_county2']) $myarr['address2 county'] = $r['address2_county2']; else $myarr['address2 county'] = $r['address2_county'];
			 if($r['address2_state2']) $myarr['address2 state'] = $r['address2_state2']; else $myarr['address2 state'] = $r['address2_state'];
			 if($r['address2_country2']) $myarr['address2 country'] = $r['address2_country2']; else $myarr['address2 country'] = $r['address2_country'];
			 $myarr['address2_zipcode'] = $r['address2_zipcode'];
			 $myarr['address2'] = $r['address2'];
			 $myarr['reference1_zipcode'] = $r['reference1_zipcode'];
			 $myarr['reference2_zipcode'] = $r['reference2_zipcode'];
			 $myarr['reference3_zipcode'] = $r['reference3_zipcode'];
			 $myarr['packageid'] = $r['packageid'];
			 $myarr['paymenthistoryid'] = $r['paymenthistoryid'];
			 $myarr['status'] = $r['status'];
			 $myarr['Apply Date'] = $r['Apply Date']; 
			 $myarr['Comments'] = $r['Comments'];

			 $returnvalue[] = $myarr; 	
		}
			//print_r($returnvalue);
			return $returnvalue;
	
	}
/* END EXPORT RESUMES */
	function validateViews(){
		$db = &$this->getDBO();
		$db->setQuery('SELECT id FROM view_resumes');

		if (!$view = $db->loadObject()){
			//echo $this->_db->getErrorMsg();
			if($this->createViews() == 1) return true; else return false;
		}else return true;
	}
	function createViews(){
		$db = &$this->getDBO();
		$query="CREATE VIEW `view_resumes`AS 
				SELECT `cat`.`cat_title` AS `categorytitle`,`salary`.`rangestart` AS `rangestart`,`salary`.`rangeend` AS `rangeend`,`jobtype`.`title` AS `jobtypetitle`,`heighesteducation`.`title` AS `heighesteducationtitle`,`nationality_country`.`name` AS `nationalitycountry`,`address_city`.`name` AS `address_city2`,`address_county`.`name` AS `address_county2`,`address_state`.`name` AS `address_state2`,`address_country`.`name` AS `address_country2`,`address1_city`.`name` AS `address1_city2`,`address1_county`.`name` AS `address1_county2`,`address1_state`.`name` AS `address1_state2`,`address1_country`.`name` AS `address1_country2`,`address2_city`.`name` AS `address2_city2`,`address2_county`.`name` AS `address2_county2`,`address2_state`.`name` AS `address2_state2`,`address2_country`.`name` AS `address2_country2`,`institute_city`.`name` AS `institute_city2`,`institute_county`.`name` AS `institute_county2`,`institute_state`.`name` AS `institute_state2`,`institute_country`.`name` AS `institute_country2`,`institute1_city`.`name` AS `institute1_city2`,`institute1_county`.`name` AS `institute1_county2`,`institute1_state`.`name` AS `institute1_state2`,`institute1_country`.`name` AS `institute1_country2`,`institute2_city`.`name` AS `institute2_city2`,`institute2_county`.`name` AS `institute2_county2`,`institute2_state`.`name` AS `institute2_state2`,`institute2_country`.`name` AS `institute2_country2`,`institute3_city`.`name` AS `institute3_city2`,`institute3_county`.`name` AS `institute3_county2`,`institute3_state`.`name` AS `institute3_state2`,`institute3_country`.`name` AS `institute3_country2`,`employer_city`.`name` AS `employer_city2`,`employer_county`.`name` AS `employer_county2`,`employer_state`.`name` AS `employer_state2`,`employer_country`.`name` AS `employer_country2`,`employer1_city`.`name` AS `employer1_city2`,`employer1_county`.`name` AS `employer1_county2`,`employer1_state`.`name` AS `employer1_state2`,`employer1_country`.`name` AS `employer1_country2`,`employer2_city`.`name` AS `employer2_city2`,`employer2_county`.`name` AS `employer2_county2`,`employer2_state`.`name` AS `employer2_state2`,`employer2_country`.`name` AS `employer2_country2`,`employer3_city`.`name` AS `employer3_city2`,`employer3_county`.`name` AS `employer3_county2`,`employer3_state`.`name` AS `employer3_state2`,`employer3_country`.`name` AS `employer3_country2`,`reference_city`.`name` AS `reference_city2`,`reference_county`.`name` AS `reference_county2`,`reference_state`.`name` AS `reference_state2`,`reference_country`.`name` AS `reference_country2`,`reference1_city`.`name` AS `reference1_city2`,`reference1_county`.`name` AS `reference1_county2`,`reference1_state`.`name` AS `reference1_state2`,`reference1_country`.`name` AS `reference1_country2`,`resume`.`id` AS `id`,`resume`.`uid` AS `uid`,`resume`.`application_title` AS `application_title`,`resume`.`first_name` AS `first_name`,`resume`.`last_name` AS `last_name`,`resume`.`middle_name` AS `middle_name`,`resume`.`gender` AS `gender`,`resume`.`email_address` AS `email_address`,`resume`.`home_phone` AS `home_phone`,`resume`.`work_phone` AS `work_phone`,`resume`.`cell` AS `cell`,`resume`.`nationality` AS `iamavailable`,`resume`.`searchable` AS `searchable`,`resume`.`photo` AS `photo`,`resume`.`job_category` AS `job_category`,`resume`.`jobsalaryrange` AS `jobsalaryrange`,`resume`.`jobtype` AS `jobtype`,`resume`.`heighestfinisheducation` AS `heighestfinisheducation`,`resume`.`address_country` AS `address_country`,`resume`.`address_state` AS `address_state`,`resume`.`address_city` AS `address_city`,`resume`.`address_zipcode` AS `address_zipcode`,`resume`.`address` AS `address`,`resume`.`institute` AS `institute`,`resume`.`institute_country` AS `institute_country`,`resume`.`institute_state` AS `institute_state`,`resume`.`institute_county` AS `institute_county`,`resume`.`institute_city` AS `institute_city`,`resume`.`institute_address` AS `institute_address`,`resume`.`institute_certificate_name` AS `institute_certificate_name`,`resume`.`institute_study_area` AS `institute_study_area`,`resume`.`employer` AS `employer`,`resume`.`employer_position` AS `employer_position`,`resume`.`employer_resp` AS `employer_resp`,`resume`.`employer_pay_upon_leaving` AS `employer_pay_upon_leaving`,`resume`.`employer_supervisor` AS `employer_supervisor`,`resume`.`employer_from_date` AS `employer_from_date`,`resume`.`employer_to_date` AS `employer_to_date`,`resume`.`employer_leave_reason` AS `employer_leave_reason`,`resume`.`employer_country` AS `employer_country`,`resume`.`employer_state` AS `employer_state`,`resume`.`employer_county` AS `employer_county`,`resume`.`employer_city` AS `employer_city`,`resume`.`employer_zip` AS `employer_zip`,`resume`.`employer_phone` AS `employer_phone`,`resume`.`employer_address` AS `employer_address`,`resume`.`institute1` AS `institute1`,`resume`.`institute1_country` AS `institute1_country`,`resume`.`institute1_state` AS `institute1_state`,`resume`.`institute1_county` AS `institute1_county`,`resume`.`institute1_city` AS `institute1_city`,`resume`.`institute1_address` AS `institute1_address`,`resume`.`institute1_certificate_name` AS `institute1_certificate_name`,`resume`.`institute1_study_area` AS `institute2`,`resume`.`institute2_country` AS `institute2_country`,`resume`.`institute2_state` AS `institute2_state`,`resume`.`institute2_county` AS `institute2_county`,`resume`.`institute2_city` AS `institute2_city`,`resume`.`institute2_address` AS `institute2_address`,`resume`.`institute2_certificate_name` AS `institute2_certificate_name`,`resume`.`institute2_study_area` AS `institute2_study_area`,`resume`.`institute3` AS `institute3`,`resume`.`institute3_country` AS `institute3_country`,`resume`.`institute3_state` AS `institute3_state`,`resume`.`institute3_county` AS `institute3_county`,`resume`.`institute3_city` AS `institute3_city`,`resume`.`institute3_address` AS `institute3_address`,`resume`.`institute3_study_area` AS `institute3_study_area`,`resume`.`institute3_certificate_name` AS `employer1`,`resume`.`employer1_position` AS `employer1_position`,`resume`.`employer1_resp` AS `employer1_resp`,`resume`.`employer1_pay_upon_leaving` AS `employer1_pay_upon_leaving`,`resume`.`employer1_supervisor` AS `employer1_supervisor`,`resume`.`employer1_from_date` AS `employer1_from_date`,`resume`.`employer1_to_date` AS `employer1_to_date`,`resume`.`employer1_leave_reason` AS `employer1_country`,`resume`.`employer1_state` AS `employer1_state`,`resume`.`employer1_county` AS `employer1_county`,`resume`.`employer1_city` AS `employer1_city`,`resume`.`employer1_zip` AS `employer1_zip`,`resume`.`employer1_phone` AS `employer1_phone`,`resume`.`employer1_address` AS `employer1_address`,`resume`.`employer2` AS `employer2`,`resume`.`employer2_position` AS `employer2_position`,`resume`.`employer2_resp` AS `employer2_resp`,`resume`.`employer2_pay_upon_leaving` AS `employer2_pay_upon_leaving`,`resume`.`employer2_supervisor` AS `employer2_supervisor`,`resume`.`employer2_from_date` AS `employer2_from_date`,`resume`.`employer2_to_date` AS `employer2_to_date`,`resume`.`employer2_leave_reason` AS `employer2_leave_reason`,`resume`.`employer2_country` AS `employer2_country`,`resume`.`employer2_state` AS `employer2_state`,`resume`.`employer2_county` AS `employer2_county`,`resume`.`employer2_city` AS `employer2_city`,`resume`.`employer2_zip` AS `employer2_zip`,`resume`.`employer2_address` AS `employer2_address`,`resume`.`employer2_phone` AS `employer2_phone`,`resume`.`employer3` AS `employer3`,`resume`.`employer3_position` AS `employer3_position`,`resume`.`employer3_resp` AS `employer3_resp`,`resume`.`employer3_pay_upon_leaving` AS `employer3_pay_upon_leaving`,`resume`.`employer3_supervisor` AS `employer3_supervisor`,`resume`.`employer3_from_date` AS `employer3_from_date`,`resume`.`employer3_to_date` AS `employer3_to_date`,`resume`.`employer3_leave_reason` AS `employer3_leave_reason`,`resume`.`employer3_country` AS `employer3_country`,`resume`.`employer3_state` AS `employer3_state`,`resume`.`employer3_county` AS `employer3_county`,`resume`.`employer3_city` AS `employer3_city`,`resume`.`employer3_zip` AS `employer3_zip`,`resume`.`employer3_address` AS `employer3_phone`,`resume`.`langugage_reading` AS `langugage_reading`,`resume`.`langugage_writing` AS `langugage_writing`,`resume`.`langugage_undarstanding` AS `langugage_undarstanding`,`resume`.`langugage_where_learned` AS `langugage_where_learned`,`resume`.`language1` AS `language1`,`resume`.`langugage1_reading` AS `langugage1_reading`,`resume`.`langugage1_writing` AS `langugage1_writing`,`resume`.`langugage1_undarstanding` AS `langugage1_undarstanding`,`resume`.`langugage1_where_learned` AS `langugage1_where_learned`,`resume`.`language2` AS `language2`,`resume`.`langugage2_reading` AS `langugage2_reading`,`resume`.`langugage2_writing` AS `langugage2_writing`,`resume`.`langugage2_undarstanding` AS `langugage2_undarstanding`,`resume`.`langugage2_where_learned` AS `langugage2_where_learned`,`resume`.`language3` AS `language3`,`resume`.`langugage3_reading` AS `langugage3_reading`,`resume`.`langugage3_writing` AS `langugage3_writing`,`resume`.`langugage3_undarstanding` AS `langugage3_undarstanding`,`resume`.`langugage3_where_learned` AS `langugage3_where_learned`,`resume`.`date_start` AS `date_start`,`resume`.`desired_salary` AS `desired_salary`,`resume`.`can_work` AS `can_work`,`resume`.`available` AS `available`,`resume`.`unalailable` AS `unalailable`,`resume`.`total_experience` AS `total_experience`,`resume`.`skills` AS `skills`,`resume`.`driving_license` AS `driving_license`,`resume`.`license_no` AS `license_no`,`resume`.`license_country` AS `license_country`,`resume`.`reference` AS `reference`,`resume`.`reference_name` AS `reference_name`,`resume`.`reference_country` AS `reference_country`,`resume`.`reference_state` AS `reference_state`,`resume`.`reference_county` AS `reference_county`,`resume`.`reference_city` AS `reference_city`,`resume`.`reference_zipcode` AS `reference_zipcode`,`resume`.`reference_address` AS `reference_address`,`resume`.`reference_phone` AS `reference_phone`,`resume`.`reference_relation` AS `reference_relation`,`resume`.`reference_years` AS `reference_years`,`resume`.`reference1` AS `reference1`,`resume`.`reference1_name` AS `reference1_name`,`resume`.`reference1_country` AS `reference1_country`,`resume`.`reference1_state` AS `reference1_state`,`resume`.`reference1_county` AS `reference1_city`,`resume`.`reference1_address` AS `reference1_address`,`resume`.`reference1_phone` AS `reference1_phone`,`resume`.`reference1_relation` AS `reference1_relation`,`resume`.`reference1_years` AS `reference1_years`,`resume`.`reference2` AS `reference2`,`resume`.`reference2_name` AS `reference2_name`,`resume`.`reference2_country` AS `reference2_country`,`resume`.`reference2_state` AS `reference2_state`,`resume`.`reference2_county` AS `reference2_county`,`resume`.`reference2_city` AS `reference2_city`,`resume`.`reference2_address` AS `reference2_address`,`resume`.`reference2_phone` AS `reference2_phone`,`resume`.`reference2_relation` AS `reference2_relation`,`resume`.`reference2_years` AS `reference2_years`,`resume`.`reference3` AS `reference3`,`resume`.`reference3_name` AS `reference3_name`,`resume`.`reference3_country` AS `reference3_country`,`resume`.`reference3_state` AS `reference3_state`,`resume`.`reference3_county` AS `reference3_county`,`resume`.`reference3_city` AS `reference3_city`,`resume`.`reference3_address` AS `reference3_address`,`resume`.`reference3_phone` AS `reference3_phone`,`resume`.`reference3_relation` AS `reference3_relation`,`resume`.`reference3_years` AS `reference3_years`,`resume`.`address1_country` AS `address1_country`,`resume`.`address1_state` AS `address1_state`,`resume`.`address1_county` AS `address1_county`,`resume`.`address1_city` AS `address1_city`,`resume`.`address1_zipcode` AS `address1_zipcode`,`resume`.`address1` AS `address1`,`resume`.`address2_country` AS `address2_country`,`resume`.`address2_state` AS `address2_state`,`resume`.`address2_county` AS `address2_county`,`resume`.`address2_city` AS `address2_city`,`resume`.`address2_zipcode` AS `address2_zipcode`,`resume`.`address2` AS `address2`,`resume`.`reference1_zipcode` AS `reference1_zipcode`,`resume`.`reference2_zipcode` AS `reference2_zipcode`,`resume`.`reference3_zipcode` AS `reference3_zipcode`,`resume`.`packageid` AS `packageid`,`resume`.`paymenthistoryid` AS `paymenthistoryid`,`resume`.`status` AS `status`,`resume`.`filename` AS `filename`,`resume`.`logofilename` AS `logofilename` from (((((((((((((((((((((((((((((((((((((((((((((((((((((((((`#__wrecruit_resume` `resume` join `#__wrecruit_categories` `cat` on((`resume`.`job_category` = `cat`.`id`))) join `#__wrecruit_jobtypes` `jobtype` on((`resume`.`jobtype` = `jobtype`.`id`))) left join `#__wrecruit_heighesteducation` `heighesteducation` on((`resume`.`heighestfinisheducation` = `heighesteducation`.`id`))) left join `#__wrecruit_countries` `nationality_country` on((`resume`.`nationality` = `nationality_country`.`code`))) left join `#__wrecruit_salaryrange` `salary` on((`resume`.`jobsalaryrange` = `salary`.`id`))) left join `#__wrecruit_cities` `address_city` on((`resume`.`address_city` = `address_city`.`code`))) left join `#__wrecruit_counties` `address_county` on((`resume`.`address_county` = `address_county`.`code`))) left join `#__wrecruit_states` `address_state` on((`resume`.`address_state` = `address_state`.`code`))) left join `#__wrecruit_countries` `address_country` on((`resume`.`address_country` = `address_country`.`code`))) left join `#__wrecruit_cities` `address1_city` on((`resume`.`address1_city` = `address1_city`.`code`))) left join `#__wrecruit_counties` `address1_county` on((`resume`.`address1_county` = `address1_county`.`code`))) left join `#__wrecruit_states` `address1_state` on((`resume`.`address1_state` = `address1_state`.`code`))) left join `#__wrecruit_countries` `address1_country` on((`resume`.`address1_country` = `address1_country`.`code`))) left join `#__wrecruit_cities` `address2_city` on((`resume`.`address2_city` = `address2_city`.`code`))) left join `#__wrecruit_counties` `address2_county` on((`resume`.`address2_county` = `address2_county`.`code`))) left join `#__wrecruit_states` `address2_state` on((`resume`.`address2_state` = `address2_state`.`code`))) left join `#__wrecruit_countries` `address2_country` on((`resume`.`address2_country` = `address2_country`.`code`))) left join `#__wrecruit_cities` `institute_city` on((`resume`.`institute_city` = `institute_city`.`code`))) left join `#__wrecruit_counties` `institute_county` on((`resume`.`institute_county` = `institute_county`.`code`))) left join `#__wrecruit_states` `institute_state` on((`resume`.`institute_state` = `institute_state`.`code`))) left join `#__wrecruit_countries` `institute_country` on((`resume`.`institute_country` = `institute_country`.`code`))) left join `#__wrecruit_cities` `institute1_city` on((`resume`.`institute1_city` = `institute1_city`.`code`))) left join `#__wrecruit_counties` `institute1_county` on((`resume`.`institute1_county` = `institute1_county`.`code`))) left join `#__wrecruit_states` `institute1_state` on((`resume`.`institute1_state` = `institute1_state`.`code`))) left join `#__wrecruit_countries` `institute1_country` on((`resume`.`institute1_country` = `institute1_country`.`code`))) left join `#__wrecruit_cities` `institute2_city` on((`resume`.`institute2_city` = `institute2_city`.`code`))) left join `#__wrecruit_counties` `institute2_county` on((`resume`.`institute2_county` = `institute2_county`.`code`))) left join `#__wrecruit_states` `institute2_state` on((`resume`.`institute2_state` = `institute2_state`.`code`))) left join `#__wrecruit_countries` `institute2_country` on((`resume`.`institute2_country` = `institute2_country`.`code`))) left join `#__wrecruit_cities` `institute3_city` on((`resume`.`institute3_city` = `institute3_city`.`code`))) left join `#__wrecruit_counties` `institute3_county` on((`resume`.`institute3_county` = `institute3_county`.`code`))) left join `#__wrecruit_states` `institute3_state` on((`resume`.`institute3_state` = `institute3_state`.`code`))) left join `#__wrecruit_countries` `institute3_country` on((`resume`.`institute3_country` = `institute3_country`.`code`))) left join `#__wrecruit_cities` `employer_city` on((`resume`.`employer_city` = `employer_city`.`code`))) left join `#__wrecruit_counties` `employer_county` on((`resume`.`employer_county` = `employer_county`.`code`))) left join `#__wrecruit_states` `employer_state` on((`resume`.`employer_state` = `employer_state`.`code`))) left join `#__wrecruit_countries` `employer_country` on((`resume`.`employer_country` = `employer_country`.`code`))) left join `#__wrecruit_cities` `employer1_city` on((`resume`.`employer1_city` = `employer1_city`.`code`))) left join `#__wrecruit_counties` `employer1_county` on((`resume`.`employer1_county` = `employer1_county`.`code`))) left join `#__wrecruit_states` `employer1_state` on((`resume`.`employer1_state` = `employer1_state`.`code`))) left join `#__wrecruit_countries` `employer1_country` on((`resume`.`employer1_country` = `employer1_country`.`code`))) left join `#__wrecruit_cities` `employer2_city` on((`resume`.`employer2_city` = `employer2_city`.`code`))) left join `#__wrecruit_counties` `employer2_county` on((`resume`.`employer2_county` = `employer2_county`.`code`))) left join `#__wrecruit_states` `employer2_state` on((`resume`.`employer2_state` = `employer2_state`.`code`))) left join `#__wrecruit_countries` `employer2_country` on((`resume`.`employer2_country` = `employer2_country`.`code`))) left join `#__wrecruit_cities` `employer3_city` on((`resume`.`employer3_city` = `employer3_city`.`code`))) left join `#__wrecruit_counties` `employer3_county` on((`resume`.`employer3_county` = `employer3_county`.`code`))) left join `#__wrecruit_states` `employer3_state` on((`resume`.`employer3_state` = `employer3_state`.`code`))) left join `#__wrecruit_countries` `employer3_country` on((`resume`.`employer3_country` = `employer3_country`.`code`))) left join `#__wrecruit_cities` `reference_city` on((`resume`.`reference_city` = `reference_city`.`code`))) left join `#__wrecruit_counties` `reference_county` on((`resume`.`reference_county` = `reference_county`.`code`))) left join `#__wrecruit_states` `reference_state` on((`resume`.`reference_state` = `reference_state`.`code`))) left join `#__wrecruit_countries` `reference_country` on((`resume`.`reference_country` = `reference_country`.`code`))) left join `#__wrecruit_cities` `reference1_city` on((`resume`.`reference1_city` = `reference1_city`.`code`))) left join `#__wrecruit_counties` `reference1_county` on((`resume`.`reference1_county` = `reference1_county`.`code`))) left join `#__wrecruit_states` `reference1_state` on((`resume`.`reference1_state` = `reference1_state`.`code`))) left join `#__wrecruit_countries` `reference1_country` on((`resume`.`reference1_country` = `reference1_country`.`code`)));
				CREATE VIEW `exportresume`AS 
				SELECT `resume`.`categorytitle` AS `categorytitle`,`resume`.`rangestart` AS `rangestart`,`resume`.`rangeend` AS `rangeend`,`resume`.`jobtypetitle` AS `jobtypetitle`,`resume`.`heighesteducationtitle` AS `heighesteducationtitle`,`resume`.`nationalitycountry` AS `nationalitycountry`,`resume`.`address_city2` AS `address_city2`,`resume`.`address_county2` AS `address_county2`,`resume`.`address_state2` AS `address_state2`,`resume`.`address_country2` AS `address_country2`,`resume`.`address1_city2` AS `address1_city2`,`resume`.`address1_county2` AS `address1_county2`,`resume`.`address1_state2` AS `address1_state2`,`resume`.`address1_country2` AS `address1_country2`,`resume`.`address2_city2` AS `address2_city2`,`resume`.`address2_county2` AS `address2_county2`,`resume`.`address2_state2` AS `address2_state2`,`resume`.`address2_country2` AS `address2_country2`,`resume`.`institute_city2` AS `institute_city2`,`resume`.`institute_county2` AS `institute_county2`,`resume`.`institute_state2` AS `institute_state2`,`resume`.`institute_country2` AS `institute_country2`,`resume`.`institute1_city2` AS `institute1_city2`,`resume`.`institute1_county2` AS `institute1_county2`,`resume`.`institute1_state2` AS `institute1_state2`,`resume`.`institute1_country2` AS `institute1_country2`,`resume`.`institute2_city2` AS `institute2_city2`,`resume`.`institute2_county2` AS `institute2_county2`,`resume`.`institute2_state2` AS `institute2_state2`,`resume`.`institute2_country2` AS `institute2_country2`,`resume`.`institute3_city2` AS `institute3_city2`,`resume`.`institute3_county2` AS `institute3_county2`,`resume`.`institute3_state2` AS `institute3_state2`,`resume`.`institute3_country2` AS `institute3_country2`,`resume`.`employer_city2` AS `employer_city2`,`resume`.`employer_county2` AS `employer_county2`,`resume`.`employer_state2` AS `employer_state2`,`resume`.`employer_country2` AS `employer_country2`,`resume`.`employer1_city2` AS `employer1_city2`,`resume`.`employer1_county2` AS `employer1_county2`,`resume`.`employer1_state2` AS `employer1_state2`,`resume`.`employer1_country2` AS `employer1_country2`,`resume`.`employer2_city2` AS `employer2_city2`,`resume`.`employer2_county2` AS `employer2_county2`,`resume`.`employer2_state2` AS `employer2_state2`,`resume`.`employer2_country2` AS `employer2_country2`,`resume`.`employer3_city2` AS `employer3_city2`,`resume`.`employer3_county2` AS `employer3_county2`,`resume`.`employer3_state2` AS `employer3_state2`,`resume`.`employer3_country2` AS `employer3_country2`,`resume`.`reference_city2` AS `reference_city2`,`resume`.`reference_county2` AS `reference_county2`,`resume`.`reference_state2` AS `reference_state2`,`resume`.`reference_country2` AS `reference_country2`,`resume`.`reference1_city2` AS `reference1_city2`,`resume`.`reference1_county2` AS `reference1_county2`,`resume`.`reference1_state2` AS `reference1_state2`,`resume`.`reference1_country2` AS `reference1_country2`,`resume`.`id` AS `id`,`resume`.`uid` AS `uid`,`resume`.`application_title` AS `application_title`,`resume`.`first_name` AS `first_name`,`resume`.`last_name` AS `last_name`,`resume`.`middle_name` AS `middle_name`,`resume`.`gender` AS `gender`,`resume`.`email_address` AS `email_address`,`resume`.`home_phone` AS `home_phone`,`resume`.`work_phone` AS `work_phone`,`resume`.`cell` AS `cell`,`resume`.`iamavailable` AS `iamavailable`,`resume`.`searchable` AS `searchable`,`resume`.`photo` AS `photo`,`resume`.`job_category` AS `job_category`,`resume`.`jobsalaryrange` AS `jobsalaryrange`,`resume`.`jobtype` AS `jobtype`,`resume`.`heighestfinisheducation` AS `heighestfinisheducation`,`resume`.`address_country` AS `address_country`,`resume`.`address_state` AS `address_state`,`resume`.`address_city` AS `address_city`,`resume`.`address_zipcode` AS `address_zipcode`,`resume`.`address` AS `address`,`resume`.`institute` AS `institute`,`resume`.`institute_country` AS `institute_country`,`resume`.`institute_state` AS `institute_state`,`resume`.`institute_county` AS `institute_county`,`resume`.`institute_city` AS `institute_city`,`resume`.`institute_address` AS `institute_address`,`resume`.`institute_certificate_name` AS `institute_certificate_name`,`resume`.`institute_study_area` AS `institute_study_area`,`resume`.`employer` AS `employer`,`resume`.`employer_position` AS `employer_position`,`resume`.`employer_resp` AS `employer_resp`,`resume`.`employer_pay_upon_leaving` AS `employer_pay_upon_leaving`,`resume`.`employer_supervisor` AS `employer_supervisor`,`resume`.`employer_from_date` AS `employer_from_date`,`resume`.`employer_to_date` AS `employer_to_date`,`resume`.`employer_leave_reason` AS `employer_leave_reason`,`resume`.`employer_country` AS `employer_country`,`resume`.`employer_state` AS `employer_state`,`resume`.`employer_county` AS `employer_county`,`resume`.`employer_city` AS `employer_city`,`resume`.`employer_zip` AS `employer_zip`,`resume`.`employer_phone` AS `employer_phone`,`resume`.`employer_address` AS `employer_address`,`resume`.`institute1` AS `institute1`,`resume`.`institute1_country` AS `institute1_country`,`resume`.`institute1_state` AS `institute1_state`,`resume`.`institute1_county` AS `institute1_county`,`resume`.`institute1_city` AS `institute1_city`,`resume`.`institute1_address` AS `institute1_address`,`resume`.`institute1_certificate_name` AS `institute1_certificate_name`,`resume`.`institute2` AS `institute2`,`resume`.`institute2_country` AS `institute2_country`,`resume`.`institute2_state` AS `institute2_state`,`resume`.`institute2_county` AS `institute2_county`,`resume`.`institute2_city` AS `institute2_city`,`resume`.`institute2_address` AS `institute2_address`,`resume`.`institute2_certificate_name` AS `institute2_certificate_name`,`resume`.`institute2_study_area` AS `institute2_study_area`,`resume`.`institute3` AS `institute3`,`resume`.`institute3_country` AS `institute3_country`,`resume`.`institute3_state` AS `institute3_state`,`resume`.`institute3_county` AS `institute3_county`,`resume`.`institute3_city` AS `institute3_city`,`resume`.`institute3_address` AS `institute3_address`,`resume`.`institute3_study_area` AS `institute3_study_area`,`resume`.`employer1` AS `employer1`,`resume`.`employer1_position` AS `employer1_position`,`resume`.`employer1_resp` AS `employer1_resp`,`resume`.`employer1_pay_upon_leaving` AS `employer1_pay_upon_leaving`,`resume`.`employer1_supervisor` AS `employer1_supervisor`,`resume`.`employer1_from_date` AS `employer1_from_date`,`resume`.`employer1_to_date` AS `employer1_to_date`,`resume`.`employer1_country` AS `employer1_country`,`resume`.`employer1_state` AS `employer1_state`,`resume`.`employer1_county` AS `employer1_county`,`resume`.`employer1_city` AS `employer1_city`,`resume`.`employer1_zip` AS `employer1_zip`,`resume`.`employer1_phone` AS `employer1_phone`,`resume`.`employer1_address` AS `employer1_address`,`resume`.`employer2` AS `employer2`,`resume`.`employer2_position` AS `employer2_position`,`resume`.`employer2_resp` AS `employer2_resp`,`resume`.`employer2_pay_upon_leaving` AS `employer2_pay_upon_leaving`,`resume`.`employer2_supervisor` AS `employer2_supervisor`,`resume`.`employer2_from_date` AS `employer2_from_date`,`resume`.`employer2_to_date` AS `employer2_to_date`,`resume`.`employer2_leave_reason` AS `employer2_leave_reason`,`resume`.`employer2_country` AS `employer2_country`,`resume`.`employer2_state` AS `employer2_state`,`resume`.`employer2_county` AS `employer2_county`,`resume`.`employer2_city` AS `employer2_city`,`resume`.`employer2_zip` AS `employer2_zip`,`resume`.`employer2_address` AS `employer2_address`,`resume`.`employer2_phone` AS `employer2_phone`,`resume`.`employer3` AS `employer3`,`resume`.`employer3_position` AS `employer3_position`,`resume`.`employer3_resp` AS `employer3_resp`,`resume`.`employer3_pay_upon_leaving` AS `employer3_pay_upon_leaving`,`resume`.`employer3_supervisor` AS `employer3_supervisor`,`resume`.`employer3_from_date` AS `employer3_from_date`,`resume`.`employer3_to_date` AS `employer3_to_date`,`resume`.`employer3_leave_reason` AS `employer3_leave_reason`,`resume`.`employer3_country` AS `employer3_country`,`resume`.`employer3_state` AS `employer3_state`,`resume`.`employer3_county` AS `employer3_county`,`resume`.`employer3_city` AS `employer3_city`,`resume`.`employer3_zip` AS `employer3_zip`,`resume`.`employer3_phone` AS `employer3_phone`,`resume`.`langugage_reading` AS `langugage_reading`,`resume`.`langugage_writing` AS `langugage_writing`,`resume`.`langugage_undarstanding` AS `langugage_undarstanding`,`resume`.`langugage_where_learned` AS `langugage_where_learned`,`resume`.`language1` AS `language1`,`resume`.`langugage1_reading` AS `langugage1_reading`,`resume`.`langugage1_writing` AS `langugage1_writing`,`resume`.`langugage1_undarstanding` AS `langugage1_undarstanding`,`resume`.`langugage1_where_learned` AS `langugage1_where_learned`,`resume`.`language2` AS `language2`,`resume`.`langugage2_reading` AS `langugage2_reading`,`resume`.`langugage2_writing` AS `langugage2_writing`,`resume`.`langugage2_undarstanding` AS `langugage2_undarstanding`,`resume`.`langugage2_where_learned` AS `langugage2_where_learned`,`resume`.`language3` AS `language3`,`resume`.`langugage3_reading` AS `langugage3_reading`,`resume`.`langugage3_writing` AS `langugage3_writing`,`resume`.`langugage3_undarstanding` AS `langugage3_undarstanding`,`resume`.`langugage3_where_learned` AS `langugage3_where_learned`,`resume`.`date_start` AS `date_start`,`resume`.`desired_salary` AS `desired_salary`,`resume`.`can_work` AS `can_work`,`resume`.`available` AS `available`,`resume`.`unalailable` AS `unalailable`,`resume`.`total_experience` AS `total_experience`,`resume`.`skills` AS `skills`,`resume`.`driving_license` AS `driving_license`,`resume`.`license_no` AS `license_no`,`resume`.`license_country` AS `license_country`,`resume`.`reference` AS `reference`,`resume`.`reference_name` AS `reference_name`,`resume`.`reference_country` AS `reference_country`,`resume`.`reference_state` AS `reference_state`,`resume`.`reference_county` AS `reference_county`,`resume`.`reference_city` AS `reference_city`,`resume`.`reference_zipcode` AS `reference_zipcode`,`resume`.`reference_address` AS `reference_address`,`resume`.`reference_phone` AS `reference_phone`,`resume`.`reference_relation` AS `reference_relation`,`resume`.`reference_years` AS `reference_years`,`resume`.`reference1` AS `reference1`,`resume`.`reference1_name` AS `reference1_name`,`resume`.`reference1_country` AS `reference1_country`,`resume`.`reference1_state` AS `reference1_state`,`resume`.`reference1_city` AS `reference1_city`,`resume`.`reference1_address` AS `reference1_address`,`resume`.`reference1_phone` AS `reference1_phone`,`resume`.`reference1_relation` AS `reference1_relation`,`resume`.`reference1_years` AS `reference1_years`,`resume`.`reference2` AS `reference2`,`resume`.`reference2_name` AS `reference2_name`,`resume`.`reference2_country` AS `reference2_country`,`resume`.`reference2_state` AS `reference2_state`,`resume`.`reference2_county` AS `reference2_county`,`resume`.`reference2_city` AS `reference2_city`,`resume`.`reference2_address` AS `reference2_address`,`resume`.`reference2_phone` AS `reference2_phone`,`resume`.`reference2_relation` AS `reference2_relation`,`resume`.`reference2_years` AS `reference2_years`,`resume`.`reference3` AS `reference3`,`resume`.`reference3_name` AS `reference3_name`,`resume`.`reference3_country` AS `reference3_country`,`resume`.`reference3_state` AS `reference3_state`,`resume`.`reference3_county` AS `reference3_county`,`resume`.`reference3_city` AS `reference3_city`,`resume`.`reference3_address` AS `reference3_address`,`resume`.`reference3_phone` AS `reference3_phone`,`resume`.`reference3_relation` AS `reference3_relation`,`resume`.`reference3_years` AS `reference3_years`,`resume`.`address1_country` AS `address1_country`,`resume`.`address1_state` AS `address1_state`,`resume`.`address1_county` AS `address1_county`,`resume`.`address1_city` AS `address1_city`,`resume`.`address1_zipcode` AS `address1_zipcode`,`resume`.`address1` AS `address1`,`resume`.`address2_country` AS `address2_country`,`resume`.`address2_state` AS `address2_state`,`resume`.`address2_county` AS `address2_county`,`resume`.`address2_city` AS `address2_city`,`resume`.`address2_zipcode` AS `address2_zipcode`,`resume`.`address2` AS `address2`,`resume`.`reference1_zipcode` AS `reference1_zipcode`,`resume`.`reference2_zipcode` AS `reference2_zipcode`,`resume`.`reference3_zipcode` AS `reference3_zipcode`,`resume`.`packageid` AS `packageid`,`resume`.`paymenthistoryid` AS `paymenthistoryid`,`resume`.`status` AS `status`,`apply`.`jobid` AS `Jobid`,`apply`.`apply_date` AS `Apply Date`,`apply`.`resumeview` AS `Resume View`,`apply`.`comments` AS `Comments` FROM (`view_resumes` `resume` JOIN `#__wrecruit_jobapply` `apply` on((`resume`.`id` = `apply`.`cvid`)));				";
				$db->setQuery( $query );
		if (!$db->queryBatch()) {
			//echo $this->_db->getErrorMsg();
			return false;
		}else return true;
	}
	function getMyStats_Employer($uid)
	{
		if (is_numeric($uid) == false) return false;
		if (($uid == 0) || ($uid == '')) return false;

                $db = &$this->getDBO();
		$results=array();
		
                // companies
                $query = "SELECT package.companiesallow,package.jobsallow,package.featuredcompaines
                    ,package.goldcompanies,package.goldjobs,package.featuredjobs
                    FROM #__wrecruit_employerpaymenthistory AS payment
                    JOIN #__wrecruit_employerpackages AS package ON package.id = payment.packageid
                    WHERE payment.uid = ".$uid."
                    AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                    AND payment.transactionverified = 1 AND payment.status = 1";
		$db->setQuery($query);
		$packages = $db->loadObjectList();
		$companiesunlimited = 0;
                $unlimitedjobs = 0;
                $unlimitedfeaturedcompaines = 0;
                $unlimitedgoldcompanies = 0;
                $unlimitedgoldjobs = 0;
                $unlimitedfeaturedjobs = 0;
		foreach($packages AS $package){
                    if($companiesunlimited == 0){
                        if ($package->companiesallow != -1) {
                                $companiesallow ="";
                                $companiesallow = $companiesallow + $package->companiesallow;
                        }else $companiesunlimited = 1;
                    }
                    if($unlimitedjobs == 0){
                        if ($package->jobsallow != -1) {
                                $jobsallow ="";
                                $jobsallow = $jobsallow + $package->jobsallow;
                        }else $unlimitedjobs = 1;
                    }
                    if($unlimitedfeaturedcompaines == 0){
			if ($package->featuredcompaines != -1) {
                                $featuredcompainesallow = "";
                                $featuredcompainesallow = $featuredcompainesallow + $package->featuredcompaines;
                        }else $unlimitedfeaturedcompaines = 1;
                    }
                    if($unlimitedgoldcompanies == 0){
			if ($package->goldcompanies != -1) {
                                $goldcompaniesallow = "";
                                $goldcompaniesallow = $goldcompaniesallow + $package->goldcompanies;
                        }else $unlimitedgoldcompanies = 1;
                    }
                    if($unlimitedgoldjobs == 0){
                        if ($package->goldjobs != -1) {
                                $goldjobsallow = "";
                                $goldjobsallow = $goldjobsallow + $package->goldjobs;
                        }else $unlimitedgoldjobs = 1;
                    }
                    if($unlimitedfeaturedjobs == 0){
			if ($package->featuredjobs != -1) {
                                $featuredjobsallow ="";
                                $featuredjobsallow = $featuredjobsallow + $package->featuredjobs;
                        }else $unlimitedfeaturedjobs = 1;
                    }

		}

                //companies
                $query = "SELECT COUNT(company.id) FROM #__wrecruit_companies AS company WHERE  uid = ".$uid;
		$db->setQuery($query);
		$totalcompanies = $db->loadResult();
		
                //jobs
                $query = "SELECT COUNT(id) FROM #__wrecruit_jobs WHERE uid = ".$uid;
		$db->setQuery($query);
		$totaljobs = $db->loadResult();

                //featured companies
                $query = "SELECT COUNT(id) FROM #__wrecruit_featuredcompanies WHERE uid = ".$uid;
		$db->setQuery($query);
		$totalfeaturedcompanies = $db->loadResult();
		
                //gold companies
                $query = "SELECT COUNT(id) FROM #__wrecruit_goldcompanies WHERE uid = ".$uid;
		$db->setQuery($query);
		$totalgoldcompanies = $db->loadResult();
		
                //gold jobs
                $query = "SELECT COUNT(id) FROM #__wrecruit_goldjobs WHERE uid = ".$uid;
		$db->setQuery($query);
		$totalgoldjobs = $db->loadResult();
		
                //featured jobs
                $query = "SELECT COUNT(id) FROM #__wrecruit_featuredjobs WHERE uid = ".$uid;
		$db->setQuery($query);
		$totalfeaturedjobs = $db->loadResult();
		
            if($companiesunlimited == 0)  $results[0]=$companiesallow;
            elseif($companiesunlimited == 1)$results[0] = -1;
            $results[1]=$totalcompanies;
		
            if($unlimitedjobs == 0) $results[2] = $jobsallow;
            elseif($unlimitedjobs == 1) $results[2] = -1;
            $results[3]=$totaljobs;
		
            if($unlimitedfeaturedcompaines == 0) $results[4]=$featuredcompainesallow;
            elseif($unlimitedfeaturedcompaines == 1)$results[4] = -1;
            $results[5]=$totalfeaturedcompanies;
		
            if($unlimitedgoldcompanies == 0) $results[6]=$goldcompaniesallow;
            elseif($unlimitedgoldcompanies == 1) $results[6] = -1;
            $results[7] = $totalgoldcompanies;
		
            if($unlimitedgoldjobs == 0) $results[8]=$goldjobsallow;
            elseif($unlimitedgoldjobs == 1) $results[8] = -1;
            $results[9]=$totalgoldjobs;
		
            if($unlimitedfeaturedjobs == 0) $results[10]=$featuredjobsallow;
            elseif($unlimitedfeaturedjobs == 1) $results[10] = -1;
            $results[11]=$totalfeaturedjobs;
        
		
            return  $results;
			
		
	}
	
        function getMyStats_JobSeeker($uid)
	{
		if (is_numeric($uid) == false) return false;
		if (($uid == 0) || ($uid == '')) return false;

                $db = &$this->getDBO();
		$results=array();

                // resume
                $query = "SELECT package.resumeallow,package.coverlettersallow,package.featuredresume,package.goldresume
                    FROM #__wrecruit_jobseekerpackages AS package
                    JOIN #__wrecruit_jobseekerpaymenthistory AS payment ON package.id = payment.packageid
                    WHERE payment.uid = ".$uid."
                    AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                    AND payment.transactionverified = 1 AND payment.status = 1";
		$db->setQuery($query);
		$packages = $db->loadObjectList();
                $unlimitedresume = 0;
                $unlimitedfeaturedresume = 0;
                $unlimitedgoldresume = 0;
                $unlimitedcoverletters = 0;
		foreach($packages AS $package){
                    if($unlimitedresume == 0){
                        if ($package->resumeallow != -1) {
                            $resumeallow = "";
                            $resumeallow = $resumeallow + $package->resumeallow;
                        }else $unlimitedresume = 1;
                    }
                    if($unlimitedfeaturedresume == 0){
			if ($package->featuredresume != -1) {
                                $featuredresumeallow ="";
                                $featuredresumeallow = $featuredresumeallow + $package->featuredresume;
                        }else $unlimitedfeaturedresume = 1;
                    }
                    if($unlimitedgoldresume == 0){
			if ($package->goldresume != -1) {
                                $goldresumeallow ="";
                                $goldresumeallow = $goldresumeallow + $package->goldresume;
                        }else $unlimitedgoldcompanies = 1;
                    }
                    if($unlimitedcoverletters == 0){
                        if ($package->coverlettersallow != -1){
                                $coverlettersallow = "";
                                $coverlettersallow = $coverlettersallow + $package->coverlettersallow;
                        }else $unlimitedcoverletters = 1;
                    }
		}

                //resume
                $query = "SELECT COUNT(id) FROM #__wrecruit_resume WHERE  uid = ".$uid;
		$db->setQuery($query);
		$totalresume = $db->loadResult();

                //featured resume
                $query = "SELECT COUNT(id) FROM #__wrecruit_featuredresumes WHERE uid = ".$uid;
		$db->setQuery($query);
		$totalfeaturedresume = $db->loadResult();

                //gold resume
                $query = "SELECT COUNT(id) FROM #__wrecruit_goldresumes WHERE uid = ".$uid;
		$db->setQuery($query);
		$totalgoldresume = $db->loadResult();

                //cover letter
                $query = "SELECT COUNT(id) FROM #__wrecruit_coverletters WHERE uid = ".$uid;
		$db->setQuery($query);
		$totalcoverletters = $db->loadResult();


            if($unlimitedresume == 0)  $results[0]=$resumeallow;
            elseif($unlimitedresume == 1)$results[0] = -1;
            $results[1]=$totalresume;

            if($unlimitedfeaturedresume == 0) $results[2]=$featuredresumeallow;
            elseif($unlimitedfeaturedresume == 1)$results[2] = -1;
            $results[3]=$totalfeaturedresume;

            if($unlimitedgoldresume == 0) $results[4]=$goldresumeallow;
            elseif($unlimitedgoldresume == 1) $results[4] = -1;
            $results[5] = $totalgoldresume;

            if($unlimitedcoverletters == 0) $results[6]=$coverlettersallow;
            elseif($unlimitedcoverletters == 1) $results[6] = -1;
            $results[7]=$totalcoverletters;

            return  $results;


	}
	

	function &getMyCompanies($u_id,$limit,$limitstart)
	{
		$result = array();
		$db = &$this->getDBO();

		if (is_numeric($u_id) == false) return false;
		if (($u_id == 0) || ($u_id == '')) return false;
		$query = "SELECT count(company.id)
                        FROM ".$db->nameQuote('#__wrecruit_companies')." AS company
                        WHERE company.uid = ".$u_id;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT company.*, cat.cat_title
			FROM ".$db->nameQuote('#__wrecruit_companies')." AS company
			JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON company.category = cat.id
			WHERE company.uid = ".$u_id;
		$db->setQuery($query, $limitstart, $limit);
		$result[0] = $db->loadObjectList();
		$result[1] = $total;

		return $result;
	}
        function &getMyDepartments($u_id,$limit,$limitstart)
	{
		$result = array();
		$db = &$this->getDBO();
		
		if (is_numeric($u_id) == false) return false;
		if (($u_id == 0) || ($u_id == '')) return false;
		$query = "SELECT count(department.id) 
                        FROM ".$db->nameQuote('#__wrecruit_departments')." AS department
                        WHERE department.uid = ".$u_id;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT department.*, company.name as companyname
			FROM ".$db->nameQuote('#__wrecruit_departments')." AS department 
			JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON company.id = department.companyid
			WHERE department.uid = ".$u_id;
		$db->setQuery($query, $limitstart, $limit);
		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		
		return $result;
	}

	function &getMyJobs($u_id,$sortby,$limit,$limitstart)
	{
		$result = array();
		$db = &$this->getDBO();

		if (is_numeric($u_id) == false) return false;
		if (($u_id == 0) || ($u_id == '')) return false;
		$listjobconfig = $this->getConfigByFor('listjob');
		$query = "SELECT count(job.id) 
                        FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
                        WHERE job.uid = ".$u_id;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT job.*, cat.cat_title
				, jobtype.title AS jobtypetitle, jobstatus.title AS jobstatustitle
				, company.name AS companyname, company.url
				, salary.rangestart, salary.rangeend, country.name AS countryname
                        FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id 
				JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code 
				, ".$db->nameQuote('#__wrecruit_categories')." AS cat 
                        WHERE job.jobcategory = cat.id AND job.uid = ".$u_id." ORDER BY  ".$sortby;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$result[0] = $this->_applications;
		$result[1] = $total;
		$result[2] = $listjobconfig;
		
		return $result;
	}

	function &getJobforForm($job_id, $uid) 
	{
		$db = &$this->getDBO();
		if (is_numeric($uid) == false) return false;
		if (($job_id != '') && ($job_id != 0)){
			if (is_numeric($job_id) == false) return false;
			$query = "SELECT job.*, cat.cat_title, salary.rangestart, salary.rangeend
			FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job 
			JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id 
			LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id 
			LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency On currency.id = job.currencyid
			WHERE job.id = ".$job_id." AND job.uid = ".$uid;			
			$db->setQuery($query);
			$this->_job = $db->loadObject();
		}
		$fieldOrdering = $this->getFieldsOrdering(2);
		foreach($fieldOrdering AS $field){
			switch($field->field){
				case "gender" : if($field->required == 1) $gernderreq = "required"; else $gernderreq = ""; break;
			}
		}
		$countries = $this->getCountries('');
		$companies = $this->getCompanies($uid);
                $categories = $this->getCategories('');
                if ( isset($this->_job) ){
			$states = $this->getStates($this->_job->country, '');
			$counties = $this->getCounties($this->_job->state, '');
			$cities = $this->getCities($this->_job->county, '');
			$lists['companies'] = JHTML::_('select.genericList', $companies , 'companyid', 'class="inputbox required" '. '', 'value', 'text', $this->_job->companyid);
			$lists['departments'] = JHTML::_('select.genericList', $this->getDepartmentsByCompanyId($this->_job->companyid,'') , 'departmentid', 'class="inputbox" '. '', 'value', 'text', $this->_job->departmentid);

			$lists['jobcategory'] = JHTML::_('select.genericList', $categories, 'jobcategory', 'class="inputbox" '. 'onChange="fj_getsubcategories(\'fj_subcategory\', this.value)"', 'value', 'text', $this->_job->jobcategory);
			$lists['subcategory'] = JHTML::_('select.genericList', $this->getSubCategoriesforCombo($this->_job->jobcategory,JText::_('JS_SUB_CATEGORY'),''), 'subcategoryid', 'class="inputbox" '. '', 'value', 'text', $this->_job->subcategoryid);
			$lists['jobtype'] = JHTML::_('select.genericList', $this->getJobType(''), 'jobtype', 'class="inputbox" '. '', 'value', 'text', $this->_job->jobtype);
			$lists['jobstatus'] = JHTML::_('select.genericList', $this->getJobStatus(''), 'jobstatus', 'class="inputbox required" '. '', 'value', 'text', $this->_job->jobstatus);
			$lists['heighesteducation'] = JHTML::_('select.genericList', $this->getHeighestEducation(''), 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', $this->_job->heighestfinisheducation);
			$lists['shift'] = JHTML::_('select.genericList', $this->getShift(''), 'shift', 'class="inputbox" '. '', 'value', 'text', $this->_job->shift);

			$lists['educationminimax'] = JHTML::_('select.genericList', $this->getMiniMax(''), 'educationminimax', 'class="inputbox" '. '', 'value', 'text', $this->_job->educationminimax);
			$lists['education'] = JHTML::_('select.genericList', $this->getHeighestEducation(''), 'educationid', 'class="inputbox" '. '', 'value', 'text', $this->_job->educationid);
			$lists['minimumeducationrange'] = JHTML::_('select.genericList', $this->getHeighestEducation(JText::_('JS_MINIMUM')), 'mineducationrange', 'class="inputbox" '. '', 'value', 'text', $this->_job->mineducationrange);
			$lists['maximumeducationrange'] = JHTML::_('select.genericList', $this->getHeighestEducation(JText::_('JS_MAXIMUM')), 'maxeducationrange', 'class="inputbox" '. '', 'value', 'text', $this->_job->maxeducationrange);

			$lists['salaryrangefrom'] = JHTML::_('select.genericList', $this->getJobSalaryRange(JText::_('JS_FROM')), 'salaryrangefrom', 'class="inputbox" '. '', 'value', 'text', $this->_job->salaryrangefrom);
			$lists['salaryrangeto'] = JHTML::_('select.genericList', $this->getJobSalaryRange(JText::_('JS_TO')), 'salaryrangeto', 'class="inputbox" '. '', 'value', 'text', $this->_job->salaryrangeto);
			$lists['salaryrangetypes'] = JHTML::_('select.genericList', $this->getSalaryRangeTypes(''), 'salaryrangetype', 'class="inputbox" '. '', 'value', 'text', $this->_job->salaryrangetype);

			$lists['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_job->country);
			if ( isset($states[1]) ) if ($states[1] != '')$lists['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', $this->_job->state);
			if ( isset($counties[1]) ) if ($counties[1] != '')$lists['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', $this->_job->county);
			if ( isset($cities[1]) ) if ($cities[1] != '')$lists['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', $this->_job->city);
			
			$lists['agefrom'] = JHTML::_('select.genericList', $this->getAges(JText::_('JS_FROM')), 'agefrom', 'class="inputbox" '. '', 'value', 'text', $this->_job->agefrom);
			$lists['ageto'] = JHTML::_('select.genericList', $this->getAges(JText::_('JS_TO')), 'ageto', 'class="inputbox" '. '', 'value', 'text', $this->_job->ageto);
			$lists['experienceminimax'] = JHTML::_('select.genericList', $this->getMiniMax(''), 'experienceminimax', 'class="inputbox" '. '', 'value', 'text', $this->_job->experienceminimax);
			$lists['experience'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_SELECT')), 'experienceid', 'class="inputbox" '. '', 'value', 'text', $this->_job->experienceid);
			$lists['minimumexperiencerange'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_MINIMUM')), 'minexperiencerange', 'class="inputbox" '. '', 'value', 'text', $this->_job->minexperiencerange);
			$lists['maximumexperiencerange'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_MAXIMUM')), 'maxexperiencerange', 'class="inputbox" '. '', 'value', 'text', $this->_job->maxexperiencerange);
			
			$lists['gender'] = JHTML::_('select.genericList', $this->getGender(JText::_('JS_DOES_NOT_MATTER')), 'gender', 'class="inputbox '.$gernderreq.'" '. '', 'value', 'text', $this->_job->gender);
			$lists['careerlevel'] = JHTML::_('select.genericList', $this->getCareerLevel(JText::_('JS_SELECT')), 'careerlevel', 'class="inputbox" '. '', 'value', 'text', $this->_job->careerlevel);
			$lists['workpermit'] = JHTML::_('select.genericList', $this->getCountries(JText::_('JS_SELECT')), 'workpermit', 'class="inputbox" '. '', 'value', 'text', $this->_job->workpermit);
			$lists['requiredtravel'] = JHTML::_('select.genericList', $this->getRequiredTravel(JText::_('JS_SELECT')), 'requiredtravel', 'class="inputbox" '. '', 'value', 'text', $this->_job->requiredtravel);
			$lists['sendemail'] = JHTML::_('select.genericList', $this->getSendEmail(), 'sendemail', 'class="inputbox" '. '', 'value', 'text', $this->_job->sendemail);
			$lists['currencyid'] = JHTML::_('select.genericList', $this->getCurrency(), 'currencyid', 'class="inputbox" '. '', 'value', 'text', $this->_job->currencyid);
			
		}else{
			if(! isset($this->_config)){ $this->getConfig('');}	
			if(isset($this->_defaultcountry))$states = $this->getStates($this->_defaultcountry, '');
			$lists['companies'] = JHTML::_('select.genericList', $companies, 'companyid', 'class="inputbox required" '.'onChange="getdepartments(\'department\', this.value)"'. '', 'value', 'text', '');
			if(isset($companies[0]['value']))$lists['departments'] = JHTML::_('select.genericList', $this->getDepartmentsByCompanyId($companies[0]['value'],'') , 'departmentid', 'class="inputbox" '. '', 'value', 'text', '');

			$lists['jobcategory'] = JHTML::_('select.genericList', $categories, 'jobcategory', 'class="inputbox" ' . 'onChange="fj_getsubcategories(\'fj_subcategory\', this.value)"', 'value', 'text', '');
			$lists['subcategory'] = JHTML::_('select.genericList', $this->getSubCategoriesforCombo($categories[0]['value'],JText::_('JS_SUB_CATEGORY'),''), 'subcategoryid', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['jobtype'] = JHTML::_('select.genericList', $this->getJobType(''), 'jobtype', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['jobstatus'] = JHTML::_('select.genericList', $this->getJobStatus(''), 'jobstatus', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['shift'] = JHTML::_('select.genericList', $this->getShift(''), 'shift', 'class="inputbox" '. '', 'value', 'text', '');

			$lists['educationminimax'] = JHTML::_('select.genericList', $this->getMiniMax(''), 'educationminimax', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['education'] = JHTML::_('select.genericList', $this->getHeighestEducation(''), 'educationid', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['minimumeducationrange'] = JHTML::_('select.genericList', $this->getHeighestEducation(JText::_('JS_MINIMUM')), 'mineducationrange', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['maximumeducationrange'] = JHTML::_('select.genericList', $this->getHeighestEducation(JText::_('JS_MAXIMUM')), 'maxeducationrange', 'class="inputbox" '. '', 'value', 'text', '');


			$lists['salaryrangefrom'] = JHTML::_('select.genericList', $this->getJobSalaryRange(JText::_('JS_FROM')), 'salaryrangefrom', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['salaryrangeto'] = JHTML::_('select.genericList', $this->getJobSalaryRange(JText::_('JS_TO')), 'salaryrangeto', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['salaryrangetypes'] = JHTML::_('select.genericList', $this->getSalaryRangeTypes(''), 'salaryrangetype', 'class="inputbox" '. '', 'value', 'text', '2');

			$lists['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_defaultcountry);
			if ( isset($states[1]) ) if ($states[1] != '')$lists['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', '');
			if ( isset($counties[1]) ) if ($counties[1] != '')$lists['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', '');
			if ( isset($cities[1]) ) if ($cities[1] != '')$lists['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', '');
			
			$lists['agefrom'] = JHTML::_('select.genericList', $this->getAges(JText::_('JS_FROM')), 'agefrom', 'class="inputbox" '. '', 'value', 'text','' );
			$lists['ageto'] = JHTML::_('select.genericList', $this->getAges(JText::_('JS_TO')), 'ageto', 'class="inputbox" '. '', 'value', 'text','' );
			$lists['experienceminimax'] = JHTML::_('select.genericList', $this->getMiniMax(''), 'experienceminimax', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['experience'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_SELECT')), 'experienceid', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['minimumexperiencerange'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_MINIMUM')), 'minexperiencerange', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['maximumexperiencerange'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_MAXIMUM')), 'maxexperiencerange', 'class="inputbox" '. '', 'value', 'text', '');

			$lists['gender'] = JHTML::_('select.genericList', $this->getGender(JText::_('JS_DOES_NOT_MATTER')), 'gender', 'class="inputbox '.$gernderreq.'" '. '', 'value', 'text', '');
			$lists['careerlevel'] = JHTML::_('select.genericList', $this->getCareerLevel(JText::_('JS_SELECT')), 'careerlevel', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['workpermit'] = JHTML::_('select.genericList', $this->getCountries(JText::_('JS_SELECT')), 'workpermit', 'class="inputbox" '. '', 'value', 'text', $this->_defaultcountry);
			$lists['requiredtravel'] = JHTML::_('select.genericList', $this->getRequiredTravel(JText::_('JS_SELECT')), 'requiredtravel', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['sendemail'] = JHTML::_('select.genericList', $this->getSendEmail(), 'sendemail', 'class="inputbox" '. '', 'value', 'text', '$this->_job->sendemail','');
			$lists['currencyid'] = JHTML::_('select.genericList', $this->getCurrency(), 'currencyid', 'class="inputbox" '. '', 'value', 'text', '');
		}
		
		$result[0] = $this->_job;
		$result[1] = $lists;
		$result[2] = $this->getUserFields(2, $job_id); // job fields , ref id
		$result[3] = $fieldOrdering; // job fields
		if ($job_id){ // not new
			$canaddreturn = $this->canAddNewJob($uid);
                        $result[4] =  1;
                        $result[5] =  $canaddreturn[1]; // package id
                }else{ // new
			$canaddreturn = $this->canAddNewJob($uid);
                        $result[4] =  $canaddreturn[0]; // can add
                        $result[5] =  $canaddreturn[1]; // package id
                }
		return $result;
	}
	function &getCurrency(){
		
		$db = & JFactory :: getDBO();
		if(! isset($this->_defaultcurrency)) $this->_defaultcurrency = $this->getDefaultCurrency();
		$q = "SELECT * FROM ".$db->nameQuote('#__wrecruit_currencies')." WHERE status = 1 AND id = " .$this->_defaultcurrency ;
		//echo $q;
		$db->setQuery($q);
		$defaultcurrency = $db->loadObject();
		$combobox=array();
		if(count($defaultcurrency)) {
			$combobox[] =  array('value' => $defaultcurrency->id,'text' => JText::_($defaultcurrency->symbol));
		}
		if(empty($defaultcurrency->id)){
			$defaultcurrency->id = -1;
		}

		$q = "SELECT * FROM ".$db->nameQuote('#__wrecruit_currencies')." WHERE status = 1 AND id != ".$defaultcurrency->id ;
		$db->setQuery($q);
		$allcurrency = $db->loadObjectList();
		if(count($allcurrency)) {
			foreach($allcurrency as $currency){
				$combobox[] =  array('value' => $currency->id,'text' => JText::_($currency->symbol));		
			}
		}
		return $combobox;
	}
	function getDefaultCurrency(){
		$db = & JFactory :: getDBO();
		$q = "SELECT id FROM ".$db->nameQuote('#__wrecruit_currencies')." AS id WHERE id.default = 1";
		$db->setQuery($q);
		$defaultValue = $db->loadResult();
		if(!$defaultValue){ 
			$q = "SELECT id FROM " .$db->nameQuote('#__wrecruit_currencies') ;
			$db->setQuery($q);
			$defaultValue = $db->loadResult();
		}
		return $defaultValue;
		
	}
	function canAddNewJob($uid) 
	{
		$db = &$this->getDBO();
		if($uid) if (is_numeric($uid) == false) return false;
		$returnvalue = array();
		$packagedetail = array();
		if (($uid == 0) || ($uid == '')){ $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; }
		$query = "SELECT package.id, package.jobsallow, package.packageexpireindays, payment.id AS paymentid, payment.created
                         , package.enforcestoppublishjob, package.enforcestoppublishjobvalue, package.enforcestoppublishjobtype
                        FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
                        JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
                        WHERE payment.uid = ".$uid."
                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                        AND payment.transactionverified = 1 AND payment.status = 1";
		//echo $query;
		$db->setQuery($query);
		$jobs = $db->loadObjectList();
		$unlimited = 0;
		foreach($jobs AS $job){
			if($unlimited == 0){
				if ($job->jobsallow != -1){
                                        $jobsallow = "";
					$jobsallow = $job->jobsallow + $jobsallow;
				}else{
                                    $unlimited = 1;
                                    $packagedetail[0] = $job->id;
                                    $packagedetail[1] = $job->paymentid;
                                    $packagedetail[2] = $job->enforcestoppublishjob;
                                    $packagedetail[3] = $job->enforcestoppublishjobvalue;
                                    $packagedetail[4] = $job->enforcestoppublishjobtype;
                                }
			}	
		}
		if ($unlimited == 0){
                    if ($jobsallow == 0) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; } //can not add new job
			$query = "SELECT COUNT(jobs.id) AS totaljobs
			FROM ".$db->nameQuote('#__wrecruit_jobs')." AS jobs
			WHERE jobs.uid = ".$uid;
			//echo $query;
			$db->setQuery($query);
			$totlajob = $db->loadResult();

			if ($jobsallow <= $totlajob) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; } //can not add new job
			else{
                            $query = "SELECT payment.id AS paymentid, package.id, package.jobsallow, package.enforcestoppublishjob, package.enforcestoppublishjobvalue, package.enforcestoppublishjobtype
                                        , (SELECT COUNT(id) FROM #__wrecruit_jobs WHERE packageid = package.id AND paymenthistoryid = payment.id AND uid = ".$uid.") AS jobavail
                                        FROM #__wrecruit_employerpaymenthistory AS payment
                                        JOIN #__wrecruit_employerpackages AS package ON package.id = payment.packageid
                                        WHERE uid = ".$uid."
                                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                                        AND payment.transactionverified = 1 AND payment.status = 1 ";
                            //echo $query;
                            $db->setQuery($query);
                            $packages = $db->loadObjectList();
                            foreach($packages AS $package){
                                    if($package->jobsallow > $package->jobavail){
                                        $packagedetail[0] = $package->id;
                                        $packagedetail[1] = $package->paymentid;
                                        $packagedetail[2] = $package->enforcestoppublishjob;
                                        $packagedetail[3] = $package->enforcestoppublishjobvalue;
                                        $packagedetail[4] = $package->enforcestoppublishjobtype;
                                    }
                            }
                            $returnvalue[0] = true;
                            $returnvalue[1] = $packagedetail;
                            return $returnvalue;
                        }
			
		}elseif ($unlimited == 1) { $returnvalue[0] = true; $returnvalue[1] = $packagedetail; return $returnvalue; } // unlimited

		$returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue;
	}
	
	function canAddNewCompany($uid) 
	{
		$db = &$this->getDBO();
		if($uid) if (is_numeric($uid) == false) return false;
		$returnvalue = array();
                $packagedetail = array();
		if (($uid == 0) || ($uid == '')) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; }

		$query = "SELECT package.id AS packageid, package.companiesallow, package.packageexpireindays, payment.id AS paymentid, payment.created
                        FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
                        JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
                        WHERE payment.uid = ".$uid."
                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                        AND payment.transactionverified = 1 AND payment.status = 1";
		$db->setQuery($query);
		$companies = $db->loadObjectList();
		$unlimited = 0;
		foreach($companies AS $company){
			if($unlimited == 0){
				if ($company->companiesallow != -1){
                                        $companiesallow = "";
					$companiesallow = $companiesallow + $company->companiesallow;
				}else{
                                    $unlimited = 1;
                                    $packagedetail[0] = $company->packageid;
                                    $packagedetail[1] = $company->paymentid;
                                }
			}	
		}
		if ($unlimited == 0){
        		if ($companiesallow == 0) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; } //can not add new company
			$query = "SELECT COUNT(company.id) AS totalcompanies
			FROM ".$db->nameQuote('#__wrecruit_companies')." AS company
			WHERE company.uid = ".$uid;
			//echo $query;
			$db->setQuery($query);
			$totalcompanies = $db->loadResult();
			
			if ($companiesallow <= $totalcompanies) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; } //can not add new company
			else{
                            $query = "SELECT payment.id AS paymentid, package.id, package.companiesallow,package.jobsallow
                                        , (SELECT COUNT(id) FROM #__wrecruit_companies WHERE packageid = package.id AND paymenthistoryid = payment.id AND uid = ".$uid.") AS jobavail
                                        FROM #__wrecruit_employerpaymenthistory AS payment
                                        JOIN #__wrecruit_employerpackages AS package ON package.id = payment.packageid
                                        WHERE payment.uid = ".$uid."
                                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                                        AND payment.transactionverified = 1 AND payment.status = 1";
                            //echo $query;
                            $db->setQuery($query);
                            $packages = $db->loadObjectList();
                            foreach($packages AS $package){
                                    if($package->jobsallow > $package->jobavail){
                                        $packagedetail[0] = $package->id;
                                        $packagedetail[1] = $package->paymentid;
                                    }
                            }
                            $returnvalue[0] = true;
                            $returnvalue[1] = $packagedetail;
                            return $returnvalue;
                        }
			
		}elseif ($unlimited == 1) { $returnvalue[0] = true; $returnvalue[1] = $packagedetail; return $returnvalue; } // unlimited
		
		return 0;
	}
/* zain */
	function canAddNewFolder($uid)
	{
		$db = &$this->getDBO();
		if (is_numeric($uid) == false) return false;
		$returnvalue = array();
                $packagedetail = array();
		if (($uid == 0) || ($uid == '')) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; }

		$query = "SELECT package.id AS packageid, package.folders, package.packageexpireindays, payment.id AS paymentid, payment.created
                        FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
                        JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
                        WHERE payment.uid = ".$uid."
                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                        AND payment.transactionverified = 1 AND payment.status = 1";
		$db->setQuery($query);
		$companies = $db->loadObjectList();
		$unlimited = 0;
		foreach($companies AS $company){
			if($unlimited == 0){
				if ($company->folders != -1){
                                        $folders = "";
					$folders = $folders + $company->folders;
				}else{
                                    $unlimited = 1;
                                    $packagedetail[0] = $company->packageid;
                                    $packagedetail[1] = $company->paymentid;
                                }
			}
		}
		if ($unlimited == 0){
        		if ($folders == 0) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; } //can not add new folder
			$query = "SELECT COUNT(folder.id) AS totalfolders
			FROM ".$db->nameQuote('#__wrecruit_folders')." AS folder
			WHERE folder.uid = ".$uid;
			//echo $query;
			$db->setQuery($query);
			$totalfolders = $db->loadResult();

			if ($folders <= $totalfolders) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; } //can not add new folder
			else{
                            $query = "SELECT payment.id AS paymentid, package.id, package.folders
                                        , (SELECT COUNT(id) FROM #__wrecruit_folders WHERE packageid = package.id AND paymenthistoryid = payment.id AND uid = ".$uid.") AS folderavail
                                        FROM #__wrecruit_employerpaymenthistory AS payment
                                        JOIN #__wrecruit_employerpackages AS package ON package.id = payment.packageid
                                        WHERE payment.uid = ".$uid."
                                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                                        AND payment.transactionverified = 1 AND payment.status = 1";
                            //echo $query;
                            $db->setQuery($query);
                            $packages = $db->loadObjectList();
                            foreach($packages AS $package){
                                    if($package->folders > $package->folderavail){
                                        $packagedetail[0] = $package->id;
                                        $packagedetail[1] = $package->paymentid;
                                    }
                            }
                            $returnvalue[0] = true;
                            $returnvalue[1] = $packagedetail;
                            return $returnvalue;
                        }

		}elseif ($unlimited == 1) { $returnvalue[0] = true; $returnvalue[1] = $packagedetail; return $returnvalue; } // unlimited

		return 0;
	}

	function canSetJobAlert($uid)
	{
		$db = &$this->getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$query = "SELECT package.id AS packageid, package.jobalertsetting, package.packageexpireindays, payment.id AS paymentid, payment.created
                        FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package
                        JOIN ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS payment ON payment.packageid = package.id
                        WHERE payment.uid = ".$uid."
                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                        AND payment.transactionverified = 1 AND payment.status = 1";
		$db->setQuery($query);
              // echo '<br>'.$query;
		$packages = $db->loadObjectList();
		$allow = 0;
		if(isset($packages)){
			foreach($packages AS $pack){
				if ($pack->jobalertsetting == 1) $allow = 1 ;
			}
		}	
		return $allow;
	}

	function canAddNewGoldCompany($uid) 
	{
		$db = &$this->getDBO();
		
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;

		$query = "SELECT package.goldcompanies, package.packageexpireindays, payment.created
                        FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
                        JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
                        WHERE payment.uid = ".$uid."
                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                        AND payment.transactionverified = 1";
		$db->setQuery($query);
		$companies = $db->loadObjectList();
		$unlimited = 0;
		foreach($companies AS $company){
			if($unlimited == 0){
				if ($company->goldcompanies != -1){
					$goldcompanies .= $company->goldcompanies;
				}else $unlimited = 1;
			}	
		}
		
		if ($unlimited == 0){
                        if ($goldcompanies == 0) return 0; //can not add new gold company

			$query = "SELECT COUNT(company.id) 
			FROM ".$db->nameQuote('#__wrecruit_goldcompanies')." AS company
			WHERE company.uid = ".$uid;
			$db->setQuery($query);
			$totalcompanies = $db->loadResult();
			
			if ($goldcompanies <= $totalcompanies) return 0; //can not add new job
			else return 1;
			
		}elseif ($unlimited == 1) return 1; // unlimited
		
		return 0;
	}

        function canAddNewFeaturedCompany($uid)
	{
		$db = &$this->getDBO();
		
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;

		$query = "SELECT package.featuredcompaines, package.packageexpireindays, payment.created
                        FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
                        JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
                        WHERE payment.uid = ".$uid."
                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                        AND payment.transactionverified = 1";
		$db->setQuery($query);
		$companies = $db->loadObjectList();
		$unlimited = 0;
		foreach($companies AS $company){
			if($unlimited == 0){
				if ($company->featuredcompaines != -1){
					$featuredcompaines .= $company->featuredcompaines;
				}else $unlimited = 1;
			}	
		}
		if ($unlimited == 0){
                    if ($featuredcompaines == 0) return 0; //can not add new job
			$query = "SELECT COUNT(company.id) 
			FROM ".$db->nameQuote('#__wrecruit_featuredcompanies')." AS company
			WHERE company.uid = ".$uid;
			//echo $query;
			$db->setQuery($query);
			$totalcompanies = $db->loadResult();
			
			if ($featuredcompaines <= $totalcompanies) return 0; //can not add new company
			else return 1;
			
		}elseif ($unlimited == 1) return 1; // unlimited
		
		return 0;
	}

	
	function canAddNewFeaturedJob($uid) 
	{
		$db = &$this->getDBO();
		
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;

		$query = "SELECT package.featuredjobs, package.packageexpireindays, payment.created
		FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid." 
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE() 
		AND payment.transactionverified = 1";
		//echo $query;
		$db->setQuery($query);
		$jobs = $db->loadObjectList();
		$unlimited = 0;
		foreach($jobs AS $job){
			if($unlimited == 0){
				if ($job->featuredjobs != -1){
					$featuredjobs = $featuredjobs + $job->featuredjobs;
				}else $unlimited = 1;
			}	
		}
		if ($unlimited == 0){
                    if ($featuredjobs == 0) return 0; //can not add new job
			$query = "SELECT COUNT(job.id) 
			FROM ".$db->nameQuote('#__wrecruit_featuredjobs')." AS job
			WHERE job.uid = ".$uid;
			//echo $query;
			$db->setQuery($query);
			$totaljobs = $db->loadResult();
			
			if ($featuredjobs <= $totaljobs) return 0; //can not add new job
			else return 1;
			
		}elseif ($unlimited == 1) return 1; // unlimited
		
		return 0;
	}


	function canAddNewGoldJob($uid) 
	{
		$db = &$this->getDBO();
		
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;

		$query = "SELECT package.goldjobs, package.packageexpireindays, payment.created
		FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid." 
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE() 
		AND payment.transactionverified = 1";
		//echo $query;
		$db->setQuery($query);
		$jobs = $db->loadObjectList();
		$unlimited = 0;
		foreach($jobs AS $job){
			if($unlimited == 0){
				if ($job->goldjobs != -1){
					$goldjobs .= $job->goldjobs;
				}else $unlimited = 1;
			}	
		}
		if ($unlimited == 0){
        		if ($goldjobs == 0) return 0; //can not add new job
		
			$query = "SELECT COUNT(job.id) 
			FROM ".$db->nameQuote('#__wrecruit_goldjobs')." AS job
			WHERE job.uid = ".$uid;
			//echo $query;
			$db->setQuery($query);
			$totaljobs = $db->loadResult();
			
			if ($goldjobs <= $totaljobs) return 0; //can not add new job
			else return 1;
			
		}elseif ($unlimited == 1) return 1; // unlimited
		
		return 0;
	}


	
	function canAddNewResume($uid) 
	{
		$db = &$this->getDBO();
		if($uid) if ((is_numeric($uid) == false)) return false;

                $returnvalue = array();
                $packagedetail = array();
                if (($uid == 0) || ($uid == '')){ $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; }
		$query = "SELECT package.id, package.resumeallow, package.packageexpireindays, payment.id AS paymentid, payment.created
		FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid."
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
		AND payment.transactionverified = 1 AND payment.status = 1";
		$db->setQuery($query);
		$resumes = $db->loadObjectList();
		$unlimited = 0;
                $resumeallow = 0;
		foreach($resumes AS $resume){
			if($unlimited == 0){
				if ($resume->resumeallow != -1){
					$resumeallow = $resume->resumeallow + $resumeallow;
				}else{
                                    $unlimited = 1;
                                    $packagedetail[0] = $resume->id;
                                    $packagedetail[1] = $resume->paymentid;
                                }
			}
		}
		if ($unlimited == 0){
                    if ($resumeallow == 0) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; } //can not add new resume
			$query = "SELECT COUNT(resume.id) AS totalresumes
			FROM ".$db->nameQuote('#__wrecruit_resume')." AS resume
			WHERE resume.uid = ".$uid;
			//echo $query;
			$db->setQuery($query);
			$totalresume = $db->loadResult();

			if ($resumeallow <= $totalresume) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; } //can not add new resume
			else{
                            $query = "SELECT payment.id AS paymentid, package.id, package.resumeallow
                                        , (SELECT COUNT(id) FROM #__wrecruit_resume WHERE packageid = package.id AND paymenthistoryid = payment.id AND uid = ".$uid.") AS resumeavail
                                        FROM #__wrecruit_jobseekerpaymenthistory AS payment
                                        JOIN #__wrecruit_jobseekerpackages AS package ON package.id = payment.packageid
                                        WHERE uid = ".$uid."
                                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                                        AND payment.transactionverified = 1 AND payment.status = 1 ";
                            //echo $query;
                            $db->setQuery($query);
                            $packages = $db->loadObjectList();
                            foreach($packages AS $package){
                                    if($package->resumeallow > $package->resumeavail){
                                        $packagedetail[0] = $package->id;
                                        $packagedetail[1] = $package->paymentid;
                                    }
                            }
                            $returnvalue[0] = true;
                            $returnvalue[1] = $packagedetail;
                            return $returnvalue;
                        }

		}elseif ($unlimited == 1) { $returnvalue[0] = true; $returnvalue[1] = $packagedetail; return $returnvalue; } // unlimited

		$returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue;

        }

	function canAddNewCoverLetter($uid) 
	{
		$db = &$this->getDBO();
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$returnvalue = array();
                $packagedetail = array();
                if (($uid == 0) || ($uid == '')){ $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; }
		$query = "SELECT package.id, package.coverlettersallow, package.packageexpireindays, payment.id AS paymentid, payment.created
		FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid."
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
		AND payment.transactionverified = 1 AND payment.status = 1";
		//echo $query;
		$db->setQuery($query);
		$resumes = $db->loadObjectList();
		$unlimited = 0;
                $coverlettersallow = 0;
		foreach($resumes AS $resume){
			if($unlimited == 0){
				if ($resume->coverlettersallow != -1){
					$coverlettersallow = $resume->coverlettersallow + $coverlettersallow;
				}else{
                                    $unlimited = 1;
                                    $packagedetail[0] = $resume->id;
                                    $packagedetail[1] = $resume->paymentid;
                                }
			}
		}
		if ($unlimited == 0){
                    if ($coverlettersallow == 0) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; } //can not add new resume
			$query = "SELECT COUNT(coverletter.id) AS totalcoverletters
			FROM ".$db->nameQuote('#__wrecruit_coverletters')." AS coverletter
			WHERE coverletter.uid = ".$uid;
			//echo $query;
			$db->setQuery($query);
			$totalcoverletters = $db->loadResult();
                        //echo '<br>to '.$totlajob;
                        //echo '<br>al '.$jobsallow;

			if ($coverlettersallow <= $totalcoverletters) { $returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue; } //can not add new resume
			else{
                            $query = "SELECT payment.id AS paymentid, package.id, package.coverlettersallow
                                        , (SELECT COUNT(id) FROM #__wrecruit_coverletters WHERE packageid = package.id AND paymenthistoryid = payment.id AND uid = ".$uid.") AS coverlettersavail
                                        FROM #__wrecruit_jobseekerpaymenthistory AS payment
                                        JOIN #__wrecruit_jobseekerpackages AS package ON package.id = payment.packageid
                                        WHERE uid = ".$uid."
                                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                                        AND payment.transactionverified = 1 AND payment.status = 1 ";
                            //echo $query;
                            $db->setQuery($query);
                            $packages = $db->loadObjectList();
                            foreach($packages AS $package){
                                    if($package->coverlettersallow > $package->coverlettersavail){
                                        $packagedetail[0] = $package->id;
                                        $packagedetail[1] = $package->paymentid;
                                    }
                            }
                            $returnvalue[0] = true;
                            $returnvalue[1] = $packagedetail;
                            return $returnvalue;
                        }

		}elseif ($unlimited == 1) { $returnvalue[0] = true; $returnvalue[1] = $packagedetail; return $returnvalue; } // unlimited

		$returnvalue[0] = false; $returnvalue[1] = $packagedetail; return $returnvalue;

        }

	function &getCompanybyIdforForm($id, $uid) 
	{
		$db = &$this->getDBO();
		if (is_numeric($uid) == false) return false;
		if (($id != '') && ($id != 0)){
			if (is_numeric($id) == false) return false;
			$query = "SELECT company.*
			FROM ".$db->nameQuote('#__wrecruit_companies')." AS company 
			WHERE company.id = ".$id;
			$db->setQuery($query);
			$company = $db->loadObject();
		}
		$countries = $this->getCountries('');

		if ( isset($company) ){
			$states = $this->getStates($company->country, '');
			$counties = $this->getCounties($company->state, '');
			$cities = $this->getCities($company->county, '');
			$lists['jobcategory'] = JHTML::_('select.genericList', $this->getCategories(''), 'category', 'class="inputbox required" '. '', 'value', 'text', $company->category);
			$lists['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $company->country);
			if ( isset($states[1]) ) if ($states[1] != '')$lists['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', $company->state);
			if ( isset($counties[1]) ) if ($counties[1] != '')$lists['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', $company->county);
			if ( isset($cities[1]) ) if ($cities[1] != '')$lists['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', $company->city);
		}else{
			if(! isset($this->_config)){ $this->getConfig('');}	
			if(isset($this->_defaultcountry))$states = $this->getStates($this->_defaultcountry, '');
			$lists['jobcategory'] = JHTML::_('select.genericList', $this->getCategories(''), 'category', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['companies'] = JHTML::_('select.genericList', $this->getCompanies($uid), 'company', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_defaultcountry);
			if ( isset($states[1]) ) if ($states[1] != '')$lists['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', '');
			if ( isset($counties[1]) ) if ($counties[1] != '')$lists['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', '');
			if ( isset($cities[1]) ) if ($cities[1] != '')$lists['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', '');
		}
		if (isset($company)) $result[0] = $company; else $result[0] = null;
		$result[1] = $lists;
//		$result[2] = $this->getUserFields(1, $company->id); // company fields, id
		$result[2] = $this->getUserFields(1, $id); // company fields, id
		$result[3] = $this->getFieldsOrdering(1); // company fields
		
		if ($id) // not new
			$result[4] = 1;
		else{ // new
                        $returnvalue = $this->canAddNewCompany($uid);
			$result[4] = $returnvalue[0];
			$result[5] = $returnvalue[1];
                }

		return $result;
	}
/* zain*/
        function sendJobAlertJobseeker($jobid){
            $db = &$this->getDBO();
		if ((is_numeric($jobid) == false) || ($jobid == 0) || ($jobid == '')) return false;
            $query = "SELECT job.title,job.jobcategory, category.cat_title AS categorytitle, subcategory.title AS subcategorytitle
                            ,subcategory.id AS subcategoryid, job.country, job.state, job.county, job.city
                            , country.name as countryname, state.name as statename, county.name as countyname, city.name as cityname

                        FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
                        JOIN ".$db->nameQuote('#__wrecruit_categories')." AS category ON job.jobcategory  = category.id
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_subcategories')." AS subcategory ON job.subcategoryid = subcategory.categoryid
                         JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
                        WHERE job.id = ".$jobid;
           // echo '<br>'.$query;
            $db->setQuery($query);
            $job = $db->loadObject();
            $countryquery = "(SELECT jobalert.contactemail
                            FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." AS jobalert
                            WHERE jobalert.categoryid = ".$job->jobcategory." 
							AND LOWER(jobalert.country) = LOWER(".$db->quote($job->country) .")";
                if($job->subcategoryid) $countryquery .= " AND jobalert.subcategoryid = ".$db->quote($job->subcategoryid);
                if($job->state) $countryquery .= " AND LOWER(jobalert.state) != LOWER(".$db->quote($job->state).")";
                if($job->county) $countryquery .= " AND LOWER(jobalert.county) != LOWER(".$db->quote($job->county).")";
                if($job->city) $countryquery .= " AND LOWER(jobalert.city) != LOWER(".$db->quote($job->city).")";
            $countryquery .= ")";
            $query = $countryquery;
            if($job->state){
                $statequery = "(SELECT jobalert.contactemail
                                FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." AS jobalert
                                WHERE jobalert.categoryid = ".$job->jobcategory." 
								AND LOWER(jobalert.country) = LOWER(".$db->quote($job->country) .")";
					if($job->subcategoryid) $statequery .= " AND jobalert.subcategoryid = ".$db->quote($job->subcategoryid);
                    if($job->state) $statequery .= " AND LOWER(jobalert.state) = LOWER(".$db->quote($job->state).")";
                    if($job->county) $statequery .= " AND LOWER(jobalert.county) != LOWER(".$db->quote($job->county).")";
                    if($job->city) $statequery .= " AND LOWER(jobalert.city) != LOWER(".$db->quote($job->city).")";
                $statequery .= ")";
               $query .= " UNION " . $statequery;
            }
            if($job->county){
                $countyquery = "(SELECT jobalert.contactemail
                                FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." AS jobalert
                                WHERE jobalert.categoryid = ".$job->jobcategory." 
								AND LOWER(jobalert.country) = LOWER(".$db->quote($job->country) .")";
					if($job->subcategoryid) $countyquery .= " AND jobalert.subcategoryid = ".$db->quote($job->subcategoryid);
                    if($job->state) $countyquery .= " AND LOWER(jobalert.state) = LOWER(".$db->quote($job->state).")";
                    if($job->county) $countyquery .= " AND LOWER(jobalert.county) = LOWER(".$db->quote($job->county).")";
                    if($job->city) $countyquery .= " AND LOWER(jobalert.city) != LOWER(".$db->quote($job->city).")";
                $countyquery .= ")";
               $query .= " UNION " . $countyquery;
            }
            if($job->city){
                $cityquery = "(SELECT jobalert.contactemail
                                FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." AS jobalert
                                WHERE jobalert.categoryid = ".$job->jobcategory." 
								AND LOWER(jobalert.country) = LOWER(".$db->quote($job->country) .")";
					if($job->subcategoryid) $cityquery .= " AND jobalert.subcategoryid = ".$db->quote($job->subcategoryid);
                    if($job->state) $cityquery .= " AND LOWER(jobalert.state) = LOWER(".$db->quote($job->state).")";
                    if($job->county) $cityquery .= " AND LOWER(jobalert.county) = LOWER(".$db->quote($job->county).")";
                    if($job->city) $cityquery .= " AND LOWER(jobalert.city) = LOWER(".$db->quote($job->city).")";
                $cityquery .= ")";
               $query .= " UNION " . $cityquery;
            }
            //echo '<br>'.$query;
            $db->setQuery($query);
            $result = $db->loadObjectList();
			
			if (isset($result)){
	            foreach ($result AS $email){
	                $bcc[] = $email->contactemail;
	                //echo '<br>'.$email->contactemail;
	            }
			}else exit;
			
            $comma = '';
            if($job->cityname) {$location = $comma.$job->cityname; $comma = ', ';}
            elseif($job->city) {$location = $comma.$job->city; $comma = ', ';}
            if($job->countyname) {$location = $comma.$job->countyname; $comma = ', ';}
            elseif($job->county) {$location = $comma.$job->county; $comma = ', ';}
            if($job->statename) {$location = $comma.$job->statename; $comma = ', ';}
            elseif($job->state) {$location = $comma.$job->state; $comma = ', ';}
            $location .= $comma.$job->countryname;
            $msgSubject = 'New Job';
            $query = "SELECT template.* FROM ".$db->nameQuote('#__wrecruit_emailtemplates') ."AS template	WHERE template.templatefor = 'job-alert'";
            $db->setQuery( $query );
            $template = $db->loadObject();
            $msgSubject = $template->subject;
            $msgBody = $template->body;

            $msgBody = str_replace('{JOB_TITLE}', $job->title, $msgBody);
            $msgBody = str_replace('{CATEGORY}', $job->categorytitle, $msgBody);
            $msgBody = str_replace('{SUB_CATEGORY}', $job->subcategorytitle, $msgBody);
            $msgBody = str_replace('{LOCATION}', $location, $msgBody);

			$config = $this->getConfigByFor('email');

            $message =& JFactory::getMailer();
            $message->addRecipient($config['mailfromaddress']); //to email
            
            //$message->addCC($cc);
            $message->addBCC($bcc);

            $message->setSubject($msgSubject);
            $message->setBody($msgBody);
            $sender = array( $config['mailfromaddress'], $config['mailfromname']);
            $message->setSender($sender);

            $message->IsHTML(true);
            //print_r($bcc) ;
            //echo '<br>'.$msgBody;
            $sent = $message->send();
			//echo '<br>Error sending email: ' . $sent->message;
            return $result;
        }
        function sendMessageEmail($messageid){
            $db = &$this->getDBO();
			if ((is_numeric($messageid) == false) || ($messageid == 0) || ($messageid == '')) return false;
            $query = "SELECT job.title as jobtitle
                        , resume.application_title as resumetitle, resume.email_address as jobseekeremail
                        , company.name as companyname, company.contactemail as employeremail
                        , message.subject, message.message, message.employerid, message.sendby
                        ,empuser.name as employername
                        ,jsuser.name as jobseekername
                    FROM ".$db->nameQuote('#__wrecruit_messages') ."AS message
                    JOIN ".$db->nameQuote('#__wrecruit_jobs') ."AS job ON job.id = message.jobid
                    JOIN ".$db->nameQuote('#__wrecruit_resume') ."AS resume ON resume.id = message.resumeid
                    JOIN ".$db->nameQuote('#__wrecruit_companies') ."AS company ON company.id = job.companyid
                    JOIN ".$db->nameQuote('#__users') ."AS empuser ON job.uid = empuser.id
                    JOIN ".$db->nameQuote('#__users') ."AS jsuser ON resume.uid = jsuser.id
                    WHERE message.id = ".$messageid;
            //echo '<br>'.$query;
            $db->setQuery( $query );
            $message = $db->loadObject();
            if($message){
                    $query = "SELECT template.* FROM ".$db->nameQuote('#__wrecruit_emailtemplates') ."AS template	WHERE template.templatefor = 'message-email'";
                    $db->setQuery( $query );
                    $template = $db->loadObject();
                    $msgSubject = $template->subject;
                    $msgBody = $template->body;
                    $msgSubject = str_replace('{COMPANY_NAME}', $message->companyname, $msgSubject);
                    $msgSubject = str_replace('{EMPLOYER_NAME}', $message->employername, $msgSubject);
                    if ($message->employerid == $message->sendby){ // send by employer
                        $msgBody = str_replace('{NAME}', $message->jobseekername, $msgBody);
                        $msgBody = str_replace('{SENDER_NAME}', $message->employername, $msgBody);
                        $to = $message->jobseekeremail;
                    }else{
                        $msgBody = str_replace('{NAME}', $message->employername, $msgBody);
                        $msgBody = str_replace('{SENDER_NAME}', $message->jobseekername, $msgBody);
                        $to = $message->employeremail;
                    }
                    $msgBody = str_replace('{JOB_TITLE}', $message->jobtitle, $msgBody);
                    $msgBody = str_replace('{COMPANY_NAME}', $message->companyname, $msgBody);
                    $msgBody = str_replace('{RESUME_TITLE}', $message->resumetitle, $msgBody);

                    $config = $this->getConfigByFor('email');

                    $message =& JFactory::getMailer();
                    $sender = array( $config['mailfromaddress'], $config['mailfromname']);
                    $message->setSender($sender);
                    $message->addRecipient($to); //to email
                    //$recipient = array( 'person1@domain.com', 'person2@domain.com', 'person3@domain.com' );
                    //$message->addCC($cc);
                    $message->addBCC($bcc);
                    $message->setSubject($msgSubject);
                    $message->setBody($msgBody);
                    $message->IsHTML(true);
                    //print_r($bcc) ;
                    //echo '<br>'.$msgSubject;
                    //echo '<br>'.$msgBody;
                    $sent = $message->send();
                    return 1;
            }else{
                return 4;
            }
        }
	function &getJobAlertbyUidforForm($uid)
	{
		$db = &$this->getDBO();
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if(! isset($this->_config)){
			$this->getConfig('');
		}	
		foreach ($this->_config as $conf){
			if ($conf->configname == 'overwrite_jobalert_settings')
				$overwrite_jobalert_settings = $conf->configvalue;
		}
		$jobalert =  $overwrite_jobalert_settings;
		if($jobalert == 0){
                $jobalert = $this->canSetJobAlert($uid);
		}
		if ($jobalert == 1){
			if (is_numeric($uid) == false) return false;
			if ($uid != 0){
	           	$query = "SELECT jobset.*
	                FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." AS jobset
					WHERE jobset.uid = ".$uid;
				//echo '<br> SQL '.$query;
				$db->setQuery($query);
				$setting = $db->loadObject();
			}
			$countries = $this->getCountries('');
	                $categories = $this->getCategories('');
	                if(isset($setting)){
				$states = $this->getStates($setting->country, '');
				$counties = $this->getCounties($setting->state, '');
				$cities = $this->getCities($setting->county, '');
				if($setting->categoryid) $categoryid = $setting->categoryid; else $categoryid = $categories[0]['value'];
				if($setting->subcategoryid) $subcategoryid = $setting->subcategoryid; else $subcategoryid = '';
				
				$lists['jobcategory'] = JHTML::_('select.genericList', $categories, 'categoryid', 'class="inputbox" ' . 'onChange="fj_getsubcategories(\'fj_subcategory\', this.value)"', 'value', 'text', $categoryid);
				$lists['subcategory'] = JHTML::_('select.genericList', $this->getSubCategoriesforCombo($categoryid,JText::_('JS_SUB_CATEGORY'),''), 'subcategoryid', 'class="inputbox" '. '', 'value', 'text', $subcategoryid );
				$lists['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $setting->country);
				if ( isset($states[1]) ) if ($states[1] != '')$lists['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', $setting->state);
				if ( isset($counties[1]) ) if ($counties[1] != '')$lists['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', $setting->county);
				if ( isset($cities[1]) ) if ($cities[1] != '')$lists['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', $setting->city);
	                }else{
				if(! isset($this->_config)){ $this->getConfig('');}
				if(isset($this->_defaultcountry))$states = $this->getStates($this->_defaultcountry, '');
				$lists['jobcategory'] = JHTML::_('select.genericList', $categories, 'categoryid', 'class="inputbox" ' . 'onChange="fj_getsubcategories(\'fj_subcategory\', this.value)"', 'value', 'text', '');
				$lists['subcategory'] = JHTML::_('select.genericList', $this->getSubCategoriesforCombo($categories[0]['value'],JText::_('JS_SUB_CATEGORY'),''), 'subcategoryid', 'class="inputbox" '. '', 'value', 'text', '');
				$lists['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_defaultcountry);
	            if ( isset($states[1]) ) if ($states[1] != '')$lists['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', '');
				if ( isset($counties[1]) ) if ($counties[1] != '')$lists['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', '');
				if ( isset($cities[1]) ) if ($cities[1] != '')$lists['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', '');
	                }
		}		
		if(isset($setting)) $result[0] = $setting;
		$result[1] = $lists;
		$result[2] = $jobalert;
		return $result;
	}
	function &getFolderResumebyFolderId($uid,$folderid,$sortby,$limit,$limitstart)
	{
		$db = &$this->getDBO();
		if($uid) if((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($folderid) == false) return false;
		$result = array();
                if (is_numeric($folderid) == false) return false;
           	$query = "SELECT COUNT(folderresume.id)
                FROM ".$db->nameQuote('#__wrecruit_folderresumes')." AS folderresume
		JOIN ".$db->nameQuote('#__wrecruit_resume')." AS resume ON folderresume.resumeid = resume.id
				WHERE folderresume.folderid = ".$folderid."
                                AND resume.published = 1 ";
                //if($jobid) $query .= " AND folderresume.jobid = ".$jobid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
		//$limit = $limit ? $limit : 5;
                if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT  apply.comments,apply.id, cat.cat_title ,apply.apply_date, jobtype.title AS jobtypetitle
                        , app.id AS appid, app.first_name, app.last_name, app.email_address, app.jobtype,app.gender
                        ,app.total_experience, app.jobsalaryrange, salary.rangestart, salary.rangeend
                        ,rating.id AS ratingid, rating.rating
                        ,app.address_city, app.address_county, app.address_state
                        ,country.name AS countryname,state.name AS statename
                        ,county.name AS countyname,city.name AS cityname
                        FROM ".$db->nameQuote('#__wrecruit_resume')." AS app
                        JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON app.jobtype = jobtype.id
                        JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON app.job_category = cat.id
                        JOIN ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  ON apply.cvid = app.id
                        LEFT JOIN  ".$db->nameQuote('#__wrecruit_resumerating')." AS rating ON (app.id=rating.resumeid AND apply.jobid=rating.jobid)
                        LEFT JOIN  ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON app.jobsalaryrange=salary.id
                        LEFT JOIN  ".$db->nameQuote('#__wrecruit_folderresumes')." AS fres ON (app.id=fres.resumeid AND apply.jobid=fres.jobid)
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON app.address_country  = country.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON app.address_state = state.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON app.address_county  = county.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON app.address_city = city.code
		WHERE fres.folderid = ".$folderid;
                //echo '<br>'.$query;
		$db->setQuery($query, $limitstart, $limit);
		$folderresume = $db->loadObjectList();
                $result[0] = $folderresume ;
		$result[1] = $total;
		return $result;
	}
/* zain */
	function &getMyFolders($uid, $limit,$limitstart)
	{
		$result = array();
		$db = &$this->getDBO();

		if (is_numeric($uid) == false) return false;
		if (($uid == 0) || ($uid == '')) return false;
		$query = "SELECT count(folder.id)
                        FROM ".$db->nameQuote('#__wrecruit_folders')." AS folder
                        WHERE folder.uid = ".$uid;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT folder.*
                                , ( SELECT count(id) FROM ".$db->nameQuote('#__wrecruit_folderresumes')." WHERE folder.id = folderid) AS noofresume
			FROM ".$db->nameQuote('#__wrecruit_folders')." AS folder
			WHERE folder.uid = ".$uid;
		$db->setQuery($query, $limitstart, $limit);
		//echo '<br>'.$query;
                $result[0] = $db->loadObjectList();
		$result[1] = $total;

		return $result;
	}

        function getMyJobsForCombo( $uid,$title ) {
                $db =& JFactory::getDBO();
                $query = "SELECT  id, title FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE jobstatus = 1 AND uid = ".$uid." ORDER BY title ASC ";
                $db->setQuery( $query );
                $rows = $db->loadObjectList();
                if ($db->getErrorNum()) {
                    echo $db->stderr();
                    return false;
                }
                $jobs = array();
                if($title)
                    $jobs[] =  array('value' => JText::_(''),'text' => $title);
                foreach($rows  as $row)	{
                    $jobs[] =  array('value' => $row->id,'text' => $row->title);
                }
                return $jobs;
        }

	function &getFolderbyIdforForm($id, $uid)
	{
		$db = &$this->getDBO();
		if (is_numeric($uid) == false) return false;
		if (($id != '') && ($id != 0)){
			if (is_numeric($id) == false) return false;
			$query = "SELECT folder.*
			FROM ".$db->nameQuote('#__wrecruit_folders')." AS folder
			WHERE folder.id = ".$id;
			$db->setQuery($query);
			$folder = $db->loadObject();
		}

		if (isset($folder)) $result[0] = $folder; else $result[0] = null;
		if ($id) // not new
			$result[1] = 1;
		else{ // new
			$returnvalue = $this->canAddNewFolder($uid);
			$result[1] = $returnvalue[0];
			$result[2] = $returnvalue[1];
                }

		return $result;
	}

	function &getJobCat($cmbfiltercountry,$cmbfilterstate,$cmbfiltercounty,$cmbfiltercity
						,$txtfiltercountry,$txtfilterstate,$txtfiltercounty,$txtfiltercity
						,$filterjobsalaryrange,$filterheighesteducation,$filterjobcategory,$filterjobtype )
	{
		if ($filterjobtype != '') if (is_numeric($filterjobtype) == false) return false;
		if ($filterjobsalaryrange != '') if (is_numeric($filterjobsalaryrange) == false) return false;
		if ($filterheighesteducation != '') if (is_numeric($filterheighesteducation) == false) return false;

		if(!$cmbfiltercountry) $cmbfiltercountry = $txtfiltercountry;
		if(!$cmbfilterstate) $cmbfilterstate = $txtfilterstate;
		if(!$cmbfiltercounty) $cmbfiltercounty = $txtfiltercounty;
		if(!$cmbfiltercity) $cmbfiltercity = $txtfiltercity;
		
		$db = &$this->getDBO();

		if(! isset($this->_config)){
			$this->getConfig('');
		}	
		foreach ($this->_config as $conf){
			if ($conf->configname == 'filter_address_fields_width')
				$address_fields_width = $conf->configvalue;
			if ($conf->configname == 'defaultcountry')
				$defaultcountry = $conf->configvalue;
			if ($conf->configname == 'hidecountry')
				$hidecountry = $conf->configvalue;
		}
		//if(!$defaultcountry) $defaultcountry = 'PK';
		//if(!$cmbfiltercountry) $cmbfiltercountry = $defaultcountry;
		$wherequery = '';
		if ($cmbfiltercountry != '') $wherequery .= " AND job.country = ".$db->Quote($cmbfiltercountry);
		elseif ($txtfiltercountry != '') $wherequery .= " AND country.name LIKE ".$db->Quote($txtfiltercountry);
		//elseif ($txtfiltercountry != '') $wherequery .= " AND country.name LIKE ".$db->Quote('%'.$db->getEscaped( $txtfiltercountry, true ).'%', false);
		if ($cmbfilterstate != '') $wherequery .= " AND job.state = ".$db->Quote($cmbfilterstate);
		elseif ($txtfilterstate != '') $wherequery .= " AND state.name LIKE ".$db->Quote($txtfilterstate);
		if ($cmbfiltercounty != '') $wherequery .= " AND job.county = ".$db->Quote($cmbfiltercounty);
		elseif ($txtfiltercounty != '') $wherequery .= " AND county.name LIKE ".$db->Quote($txtfiltercounty);
		if ($cmbfiltercity != '') $wherequery .= " AND job.city = ".$db->Quote($cmbfiltercity);
		elseif ($txtfiltercity != '') $wherequery .= " AND city.name LIKE ".$db->Quote($txtfiltercity);
		
		//if ($filterjobcategory != '') $wherequery .= " AND job.jobcategory = ".$filterjobcategory;
		if ($filterjobtype != '') $wherequery .= " AND job.jobtype = ".$filterjobtype;
		if ($filterjobsalaryrange != '') $wherequery .= " AND job.jobsalaryrange = ".$filterjobsalaryrange;
		if ($filterheighesteducation != '') $wherequery .= " AND job.heighestfinisheducation = ".$filterheighesteducation;

		$curdate = date('Y-m-d H:i:s');
		$inquery =  " (SELECT COUNT(job.id) from ".$db->nameQuote('#__wrecruit_jobs')."  AS job WHERE cat.id = job.jobcategory AND job.status = 1 AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
		$inquery .= $wherequery. " ) as catinjobs";

		$query =  "SELECT  DISTINCT cat.id, cat.cat_title, ";
		$query .= $inquery;
		$query .=  " FROM ".$db->nameQuote('#__wrecruit_categories')." AS cat 
					LEFT JOIN ".$db->nameQuote('#__wrecruit_jobs')."  AS job ON cat.id = job.jobcategory
					LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code 
					LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code 
					LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code 
					LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code 
					WHERE cat.isactive = 1 ";
		$query .=  " ORDER BY cat.cat_title ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$this->_applications = $db->loadObjectList();

		$jobtype = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
		$jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));
		$heighesteducation = $this->getHeighestEducation(JText::_('JS_SELECT_EDUCATION'));

		$jobcategories[] =  array('value' => '','text' => JText::_('JS_ALL_CATEGORIES'));
		$job_categories = $jobcategories;
			
		$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SELECT_SALARY'));
		if($hidecountry != 1)$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
		if($cmbfiltercountry != '') $states = $this->getStates($cmbfiltercountry, JText::_('JS_SELECT_STATE'));
		if ($cmbfilterstate != '') $counties = $this->getCounties($cmbfilterstate, JText::_('JS_SELECT_COUNTY'));
		if ($cmbfiltercounty != '') $cities = $this->getCities($cmbfiltercounty, JText::_('JS_SELECT_CITY'));
		
		
		if($hidecountry != 1)$filterlists['country'] = JHTML::_('select.genericList', $countries, 'cmbfilter_country','class="inputbox" style="width:'.$address_fields_width.'px;" '.'onChange="filter_dochange(\'filter_state\', this.value)"', 'value', 'text', $cmbfiltercountry);
		if ( isset($states[1]) ) if ($states[1] != '') $filterlists['state'] = JHTML::_('select.genericList', $states, 'cmbfilter_state', 'class="inputbox"  style="width:'.$address_fields_width.'px;"'. 'onChange="filter_dochange(\'filter_county\', this.value)"', 'value', 'text', $cmbfilterstate);
		if ( isset($counties[1]) ) if ($counties[1] != '') $filterlists['county'] = JHTML::_('select.genericList', $counties, 'cmbfilter_county', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_city\', this.value)"', 'value', 'text', $cmbfiltercounty);
		if ( isset($cities[1]) ) if ($cities[1] != '') $filterlists['city'] = JHTML::_('select.genericList', $cities, 'cmbfilter_city', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. '', 'value', 'text', $cmbfiltercity);

		$filterlists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'filter_jobcategory', 'class="inputbox" '. '', 'value', 'text', $filterjobcategory);
		$filterlists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'filter_jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', $filterjobsalaryrange);
		$filterlists['jobtype'] = JHTML::_('select.genericList', $jobtype, 'filter_jobtype', 'class="inputbox" '. '', 'value', 'text', $filterjobtype);
		$filterlists['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'filter_heighesteducation', 'class="inputbox" '. '', 'value', 'text', $filterheighesteducation);

		$filtervalues['state'] = $txtfilterstate;
		$filtervalues['county'] = $txtfiltercounty;
		$filtervalues['city'] = $txtfiltercity;
		
		$result[0] = $this->_applications;
		$result[1] = '';
		$result[2] = $filterlists;
		$result[3] = $filtervalues;
		
		return $result;
	}
	
	function &getUserFields($fieldfor, $id)
	{
		$db = &$this->getDBO();
		//if (isset($id) == false) return false;
		$result;
		//if (is_numeric($id) == false) return $result;
		$field = array();
		$result = array();
		$query =  "SELECT  * FROM ".$db->nameQuote('#__wrecruit_userfields')." 
					WHERE published = 1 AND fieldfor = ". $fieldfor;
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		
		$i = 0;
		foreach ($rows as $row){
			$field[0] = $row;
			if ($id != ""){
				$query =  "SELECT  * FROM ".$db->nameQuote('#__wrecruit_userfield_data')." WHERE referenceid = ".$id." AND field = ". $row->id;
				$db->setQuery($query);
				$data = $db->loadObject();
				$field[1] = $data;
			}
			if ($row->type == "select"){
				$query =  "SELECT  * FROM ".$db->nameQuote('#__wrecruit_userfieldvalues')." WHERE field = ". $row->id;
				$db->setQuery($query);
				$values = $db->loadObjectList();
				$field[2] = $values;
			}
			$result[] = $field;
			$i++;
		}
		return $result;
	}
	
	function &getUserFieldsForView($fieldfor, $id)
	{
		$db = &$this->getDBO();
		//if (isset($id) == false) return false;
		$result;
		//if (is_numeric($id) == false) return $result;
		$field = array();
		$result = array();
		$query =  "SELECT  * FROM ".$db->nameQuote('#__wrecruit_userfields')." 
					WHERE published = 1 AND fieldfor = ". $fieldfor;
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		
		$i = 0;
		foreach ($rows as $row){
			$field[0] = $row;
			if ($id != ""){
				$query =  "SELECT  * FROM ".$db->nameQuote('#__wrecruit_userfield_data')." WHERE referenceid = ".$id." AND field = ". $row->id;
				$db->setQuery($query);
				$data = $db->loadObject();
				$field[1] = $data;
			}
			if ($row->type == "select"){
				$query =  "SELECT  value.* FROM ".$db->nameQuote('#__wrecruit_userfieldvalues')." value
				JOIN ".$db->nameQuote('#__wrecruit_userfield_data')." udata ON udata.data = value.id
				WHERE value.field = ". $row->id;
				$db->setQuery($query);
				//echo '<br> sql '.$query;
				$value = $db->loadObject();
				$field[2] = $value;
			}
			$result[] = $field;
			$i++;
		}
		return $result;
	}
	
	function &getFieldsOrdering($fieldfor)
	{
		$db = &$this->getDBO();
		$query =  "SELECT  * FROM ".$db->nameQuote('#__wrecruit_fieldsordering')." 
					WHERE published = 1 AND fieldfor =  ". $fieldfor
					." ORDER BY ordering";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$fields = $db->loadObjectList();
		return $fields;
	}
	
	function &getJobsbyCategory($uid,$cat_id,$cmbfiltercountry,$cmbfilterstate,$cmbfiltercounty,$cmbfiltercity
										,$txtfiltercountry,$txtfilterstate,$txtfiltercounty,$txtfiltercity
										,$filterjobsalaryrange,$filterheighesteducation,$filterjobcategory,$filterjobtype 
										,$sortby,$limit,$limitstart)



	{

		if(!$cmbfiltercountry) $cmbfiltercountry = $txtfiltercountry;
		if(!$cmbfilterstate) $cmbfilterstate = $txtfilterstate;
		if(!$cmbfiltercounty) $cmbfiltercounty = $txtfiltercounty;
		if(!$cmbfiltercity) $cmbfiltercity = $txtfiltercity;

		$db = &$this->getDBO();
		$result = array();
		if (is_numeric($cat_id) == false) return false;
		if ($filterjobtype != '') if (is_numeric($filterjobtype) == false) return false;
		if ($filterjobsalaryrange != '') if (is_numeric($filterjobsalaryrange) == false) return false;
		if ($filterheighesteducation != '') if (is_numeric($filterheighesteducation) == false) return false;

		if(! isset($this->_config)){
			$this->getConfig('');
		}	
		foreach ($this->_config as $conf){
			if ($conf->configname == 'filter_address_fields_width')
				$address_fields_width = $conf->configvalue;
			if ($conf->configname == 'defaultcountry')
				$defaultcountry = $conf->configvalue;
			if ($conf->configname == 'hidecountry')
				$hidecountry = $conf->configvalue;
		}
		//if(!$defaultcountry) $defaultcountry = 'PK';
		//if(!$cmbfiltercountry) $cmbfiltercountry = $defaultcountry;
		$listjobconfig = $this->getConfigByFor('listjob');
		$wherequery = '';
		if ($cmbfiltercountry != '') $wherequery .= " AND job.country = ".$db->Quote($cmbfiltercountry);
		elseif ($txtfiltercountry != '') $wherequery .= " AND country.name LIKE ".$db->Quote($txtfiltercountry);
		if ($cmbfilterstate != '') $wherequery .= " AND job.state = ".$db->Quote($cmbfilterstate);
		elseif ($txtfilterstate != '') $wherequery .= " AND state.name LIKE ".$db->Quote($txtfilterstate);
		if ($cmbfiltercounty != '') $wherequery .= " AND job.county = ".$db->Quote($cmbfiltercounty);
		elseif ($txtfiltercounty != '') $wherequery .= " AND county.name LIKE ".$db->Quote($txtfiltercounty);
		if ($cmbfiltercity != '') $wherequery .= " AND job.city = ".$db->Quote($cmbfiltercity);
		elseif ($txtfiltercity != '') $wherequery .= " AND city.name LIKE ".$db->Quote($txtfiltercity);

		//if ($filterjobcategory != '') $wherequery .= " AND job.jobcategory = ".$filterjobcategory;
		if ($filterjobtype != '') $wherequery .= " AND job.jobtype = ".$filterjobtype;
		//if ($filterjobsalaryrange != '') $wherequery .= " AND job.jobsalaryrange = ".$filterjobsalaryrange;
		if ($filterheighesteducation != '') $wherequery .= " AND job.heighestfinisheducation = ".$filterheighesteducation;

		$curdate = date('Y-m-d H:i:s');
                // sub categories query
                if ($listjobconfig['subcategories'] == 1) {
                    $inquery =  " (SELECT COUNT(job.id) from ".$db->nameQuote('#__wrecruit_jobs')."  AS job WHERE subcat.id = job.subcategoryid AND job.status = 1 AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
                    $inquery .= $wherequery. " ) as jobsinsubcat";

                    $query =  "SELECT  DISTINCT subcat.id, subcat.title, ";
                    $query .= $inquery;
                    $query .=  " FROM ".$db->nameQuote('#__wrecruit_subcategories')." AS subcat
                                            LEFT JOIN ".$db->nameQuote('#__wrecruit_jobs')."  AS job ON subcat.id = job.subcategoryid
                                            LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
                                            LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code
                                            LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code
                                            LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
                                            WHERE subcat.status = 1 AND categoryid = ".$cat_id;
                    $query .=  " ORDER BY subcat.title ";
                    //echo '<br> SQL '.$query;
                    $db->setQuery($query);
                    $subcategories = $db->loadObjectList();
                }
                // end sub categories

                $query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code 
				WHERE job.jobcategory = cat.id AND job.status = 1  AND cat.id = ".$cat_id." 
				AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
		$query .= $wherequery;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
                if ($total != 0){
                    $query = "SELECT job.*, cat.cat_title, jobtype.title AS jobtype, jobstatus.title AS jobstatus
                                            , company.id AS companyid, company.name AS companyname, company.url
											, salaryfrom.rangestart AS salaryfrom, salaryto.rangeend AS salaryto, salarytype.title AS salaytype
                                            , country.name AS countryname, state.name AS statename, county.name AS countyname, city.name AS cityname ,currency.symbol
                                    FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
                                    JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
                                    JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
                                    JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryfrom ON job.salaryrangefrom = salaryfrom.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryto ON job.salaryrangeto = salaryto.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrangetypes')." AS salarytype ON job.salaryrangetype = salarytype.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = job.currencyid
                                    WHERE job.status = 1  AND cat.id = ".$cat_id ."
                                    AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);

                    $query .= $wherequery." ORDER BY  ".$sortby;
                    //echo '<br> SQL '.$query;
                    $db->setQuery($query, $limitstart, $limit);
                    $jobs = $db->loadObjectList();
                }else{
                    $query = "SELECT cat.cat_title
                                    FROM ".$db->nameQuote('#__wrecruit_categories')." AS cat
                                    WHERE cat.id = ".$cat_id;
                    $db->setQuery($query);
                    $category = $db->loadObject();
                }
		//echo '<br> SQL '.$query;

		$jobtype = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
		$jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));
		$heighesteducation = $this->getHeighestEducation(JText::_('JS_SELECT_EDUCATION'));

		$job_categories = $this->getCategories(JText::_('JS_SELECT_CATEGORY'));
		$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SELECT_SALARY'));
		if($hidecountry != 1)$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
		if($cmbfiltercountry != '') $states = $this->getStates($cmbfiltercountry, JText::_('JS_SELECT_STATE'));
		if ($cmbfilterstate != '') $counties = $this->getCounties($cmbfilterstate, JText::_('JS_SELECT_COUNTY'));
		if ($cmbfiltercounty != '') $cities = $this->getCities($cmbfiltercounty, JText::_('JS_SELECT_CITY'));
		
		
		if($hidecountry != 1)$filterlists['country'] = JHTML::_('select.genericList', $countries, 'cmbfilter_country','class="inputbox"  style="width:'.$address_fields_width.'px;" '.'onChange="filter_dochange(\'filter_state\', this.value)"', 'value', 'text', $cmbfiltercountry);
		if ( isset($states[1]) ) if ($states[1] != '') $filterlists['state'] = JHTML::_('select.genericList', $states, 'cmbfilter_state', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_county\', this.value)"', 'value', 'text', $cmbfilterstate);
		if ( isset($counties[1]) ) if ($counties[1] != '') $filterlists['county'] = JHTML::_('select.genericList', $counties, 'cmbfilter_county', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_city\', this.value)"', 'value', 'text', $cmbfiltercounty);
		if ( isset($cities[1]) ) if ($cities[1] != '') $filterlists['city'] = JHTML::_('select.genericList', $cities, 'cmbfilter_city', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. '', 'value', 'text', $cmbfiltercity);

		$filterlists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'filter_jobcategory', 'class="inputbox" '. '', 'value', 'text', $filterjobcategory);
		$filterlists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'filter_jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', $filterjobsalaryrange);
		$filterlists['jobtype'] = JHTML::_('select.genericList', $jobtype, 'filter_jobtype', 'class="inputbox" '. '', 'value', 'text', $filterjobtype);
		$filterlists['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'filter_heighesteducation', 'class="inputbox" '. '', 'value', 'text', $filterheighesteducation);

		$filtervalues['state'] = $txtfilterstate;
		$filtervalues['county'] = $txtfiltercounty;
		$filtervalues['city'] = $txtfiltercity;
		
                $packageexpiry = $this->getJobSeekerPackageExpiry($uid);
                if($packageexpiry == 1){ //package expire or user not login
                   $listjobconfigs = array();
                    $listjobconfigs['lj_title'] = $listjobconfig['visitor_lj_title'];
                    $listjobconfigs['lj_category'] = $listjobconfig['visitor_lj_category'];
                    $listjobconfigs['lj_jobtype'] = $listjobconfig['visitor_lj_jobtype'];
                    $listjobconfigs['lj_jobstatus'] = $listjobconfig['visitor_lj_jobstatus'];
                    $listjobconfigs['lj_company'] = $listjobconfig['visitor_lj_company'];
                    $listjobconfigs['lj_companysite'] = $listjobconfig['visitor_lj_companysite'];
                    $listjobconfigs['lj_country'] = $listjobconfig['visitor_lj_country'];
                    $listjobconfigs['lj_state'] = $listjobconfig['visitor_lj_state'];
                    $listjobconfigs['lj_county'] = $listjobconfig['visitor_lj_county'];
                    $listjobconfigs['lj_city'] = $listjobconfig['visitor_lj_city'];
                    $listjobconfigs['lj_salary'] = $listjobconfig['visitor_lj_salary'];
                    $listjobconfigs['lj_created'] = $listjobconfig['visitor_lj_created'];
                    $listjobconfigs['lj_noofjobs'] = $listjobconfig['visitor_lj_noofjobs'];
                    $listjobconfigs['subcategories'] = $listjobconfig['subcategories'];
                    $listjobconfigs['subcategories_all'] = $listjobconfig['subcategories_all'];
                    $listjobconfigs['subcategories_colsperrow'] = $listjobconfig['subcategories_colsperrow'];
                    $listjobconfigs['subcategoeis_max_hight'] = $listjobconfig['subcategoeis_max_hight'];
                    $listjobconfigs['lj_description'] = $listjobconfig['visitor_lj_description'];
                    $listjobconfigs['lj_shortdescriptionlenght'] = $listjobconfig['lj_shortdescriptionlenght'];
                    $listjobconfigs['lj_joblistingstyle'] = $listjobconfig['lj_joblistingstyle'];
                }else $listjobconfigs = $listjobconfig; // user

                 if(isset($jobs))$result[0] = $jobs;
		$result[1] = $total;
		$result[2] = $filterlists;
		$result[3] = $filtervalues;
		$result[4] = $listjobconfigs;
		$result[5] = $subcategories;
		if(isset($category)) $result[6] = $category;
		
		return $result;
	}
	function &getJobsbySubCategory($cat_id,$cmbfiltercountry,$cmbfilterstate,$cmbfiltercounty,$cmbfiltercity
										,$txtfiltercountry,$txtfilterstate,$txtfiltercounty,$txtfiltercity
										,$filterjobsalaryrange,$filterheighesteducation,$filterjobcategory,$filterjobtype
										,$sortby,$limit,$limitstart)
	{

		if(!$cmbfiltercountry) $cmbfiltercountry = $txtfiltercountry;
		if(!$cmbfilterstate) $cmbfilterstate = $txtfilterstate;
		if(!$cmbfiltercounty) $cmbfiltercounty = $txtfiltercounty;
		if(!$cmbfiltercity) $cmbfiltercity = $txtfiltercity;

		$db = &$this->getDBO();
		$result = array();
		if (is_numeric($cat_id) == false) return false;
		if ($filterjobtype != '') if (is_numeric($filterjobtype) == false) return false;
		if ($filterjobsalaryrange != '') if (is_numeric($filterjobsalaryrange) == false) return false;
		if ($filterheighesteducation != '') if (is_numeric($filterheighesteducation) == false) return false;

		if(! isset($this->_config)){
			$this->getConfig('');
		}
		foreach ($this->_config as $conf){
			if ($conf->configname == 'filter_address_fields_width')
				$address_fields_width = $conf->configvalue;
		}
		$listjobconfig = $this->getConfigByFor('listjob');
		$wherequery = '';
		if ($cmbfiltercountry != '') $wherequery .= " AND job.country = ".$db->Quote($cmbfiltercountry);
		elseif ($txtfiltercountry != '') $wherequery .= " AND country.name LIKE ".$db->Quote($txtfiltercountry);
		if ($cmbfilterstate != '') $wherequery .= " AND job.state = ".$db->Quote($cmbfilterstate);
		elseif ($txtfilterstate != '') $wherequery .= " AND state.name LIKE ".$db->Quote($txtfilterstate);
		if ($cmbfiltercounty != '') $wherequery .= " AND job.county = ".$db->Quote($cmbfiltercounty);
		elseif ($txtfiltercounty != '') $wherequery .= " AND county.name LIKE ".$db->Quote($txtfiltercounty);
		if ($cmbfiltercity != '') $wherequery .= " AND job.city = ".$db->Quote($cmbfiltercity);
		elseif ($txtfiltercity != '') $wherequery .= " AND city.name LIKE ".$db->Quote($txtfiltercity);

		//if ($filterjobcategory != '') $wherequery .= " AND job.jobcategory = ".$filterjobcategory;
		if ($filterjobtype != '') $wherequery .= " AND job.jobtype = ".$filterjobtype;
		//if ($filterjobsalaryrange != '') $wherequery .= " AND job.jobsalaryrange = ".$filterjobsalaryrange;
		if ($filterheighesteducation != '') $wherequery .= " AND job.heighestfinisheducation = ".$filterheighesteducation;

		$curdate = date('Y-m-d H:i:s');

                $query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_subcategories')." AS subcat ON job.subcategoryid = subcat.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
				WHERE job.status = 1  AND subcat.id = ".$cat_id."
				AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
		$query .= $wherequery;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;

                if ($total != 0){
                    $query = "SELECT job.*, cat.id as cat_id,cat.cat_title, subcat.title as subcategory, jobtype.title AS jobtype, jobstatus.title AS jobstatus
                                            , company.id AS companyid, company.name AS companyname, company.url
											, salaryfrom.rangestart AS salaryfrom, salaryto.rangeend AS salaryto, salarytype.title AS salaytype
                                            , country.name AS countryname, state.name AS statename, county.name AS countyname, city.name AS cityname ,currency.symbol
                                    FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
                                    JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
                                    JOIN ".$db->nameQuote('#__wrecruit_subcategories')." AS subcat ON job.subcategoryid = subcat.id
                                    JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
                                    JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryfrom ON job.salaryrangefrom = salaryfrom.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryto ON job.salaryrangeto = salaryto.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrangetypes')." AS salarytype ON job.salaryrangetype = salarytype.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = job.currencyid
                                    WHERE job.status = 1  AND subcat.id = ".$cat_id ."
                                    AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);

                    $query .= $wherequery." ORDER BY  ".$sortby;
                }else{
                    $query = "SELECT cat.id as cat_id, cat.cat_title, subcat.title as subcategory
                                    FROM ".$db->nameQuote('#__wrecruit_categories')." AS cat
                                    JOIN ".$db->nameQuote('#__wrecruit_subcategories')." AS subcat ON subcat.categoryid = cat.id
                                    WHERE subcat.id = ".$cat_id;

                }
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$jobtype = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
		$jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));
		$heighesteducation = $this->getHeighestEducation(JText::_('JS_SELECT_EDUCATION'));

		$job_categories = $this->getCategories(JText::_('JS_SELECT_CATEGORY'));
		$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SELECT_SALARY'));
		$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
		if($cmbfiltercountry != '') $states = $this->getStates($cmbfiltercountry, JText::_('JS_SELECT_STATE'));
		if ($cmbfilterstate != '') $counties = $this->getCounties($cmbfilterstate, JText::_('JS_SELECT_COUNTY'));
		if ($cmbfiltercounty != '') $cities = $this->getCities($cmbfiltercounty, JText::_('JS_SELECT_CITY'));


		$filterlists['country'] = JHTML::_('select.genericList', $countries, 'cmbfilter_country','class="inputbox"  style="width:'.$address_fields_width.'px;" '.'onChange="filter_dochange(\'filter_state\', this.value)"', 'value', 'text', $cmbfiltercountry);
		if ( isset($states[1]) ) if ($states[1] != '') $filterlists['state'] = JHTML::_('select.genericList', $states, 'cmbfilter_state', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_county\', this.value)"', 'value', 'text', $cmbfilterstate);
		if ( isset($counties[1]) ) if ($counties[1] != '') $filterlists['county'] = JHTML::_('select.genericList', $counties, 'cmbfilter_county', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_city\', this.value)"', 'value', 'text', $cmbfiltercounty);
		if ( isset($cities[1]) ) if ($cities[1] != '') $filterlists['city'] = JHTML::_('select.genericList', $cities, 'cmbfilter_city', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. '', 'value', 'text', $cmbfiltercity);

		$filterlists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'filter_jobcategory', 'class="inputbox" '. '', 'value', 'text', $filterjobcategory);
		$filterlists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'filter_jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', $filterjobsalaryrange);
		$filterlists['jobtype'] = JHTML::_('select.genericList', $jobtype, 'filter_jobtype', 'class="inputbox" '. '', 'value', 'text', $filterjobtype);
		$filterlists['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'filter_heighesteducation', 'class="inputbox" '. '', 'value', 'text', $filterheighesteducation);

		$filtervalues['state'] = $txtfilterstate;
		$filtervalues['county'] = $txtfiltercounty;
		$filtervalues['city'] = $txtfiltercity;

                $packageexpiry = $this->getJobSeekerPackageExpiry($uid);
                if($packageexpiry == 1){ //package expire or user not login
                   $listjobconfigs = array();
                    $listjobconfigs['lj_title'] = $listjobconfig['visitor_lj_title'];
                    $listjobconfigs['lj_category'] = $listjobconfig['visitor_lj_category'];
                    $listjobconfigs['lj_jobtype'] = $listjobconfig['visitor_lj_jobtype'];
                    $listjobconfigs['lj_jobstatus'] = $listjobconfig['visitor_lj_jobstatus'];
                    $listjobconfigs['lj_company'] = $listjobconfig['visitor_lj_company'];
                    $listjobconfigs['lj_companysite'] = $listjobconfig['visitor_lj_companysite'];
                    $listjobconfigs['lj_country'] = $listjobconfig['visitor_lj_country'];
                    $listjobconfigs['lj_state'] = $listjobconfig['visitor_lj_state'];
                    $listjobconfigs['lj_county'] = $listjobconfig['visitor_lj_county'];
                    $listjobconfigs['lj_city'] = $listjobconfig['visitor_lj_city'];
                    $listjobconfigs['lj_salary'] = $listjobconfig['visitor_lj_salary'];
                    $listjobconfigs['lj_created'] = $listjobconfig['visitor_lj_created'];
                    $listjobconfigs['lj_noofjobs'] = $listjobconfig['visitor_lj_noofjobs'];
                    $listjobconfigs['subcategories'] = $listjobconfig['subcategories'];
                    $listjobconfigs['subcategories_all'] = $listjobconfig['subcategories_all'];
                    $listjobconfigs['subcategories_colsperrow'] = $listjobconfig['subcategories_colsperrow'];
                    $listjobconfigs['subcategoeis_max_hight'] = $listjobconfig['subcategoeis_max_hight'];
                    $listjobconfigs['lj_description'] = $listjobconfig['visitor_lj_description'];
                    $listjobconfigs['lj_shortdescriptionlenght'] = $listjobconfig['lj_shortdescriptionlenght'];
                    $listjobconfigs['lj_joblistingstyle'] = $listjobconfig['lj_joblistingstyle'];
                }else $listjobconfigs = $listjobconfig; // user

                $result[0] = $this->_applications;
		$result[1] = $total;
		$result[2] = $filterlists;
		$result[3] = $filtervalues;
		$result[4] = $listjobconfigs;

		return $result;
	}

	function &getJobsbyCompany($companyid,$cmbfiltercountry,$cmbfilterstate,$cmbfiltercounty,$cmbfiltercity
										,$txtfiltercountry,$txtfilterstate,$txtfiltercounty,$txtfiltercity
										,$filterjobsalaryrange,$filterheighesteducation,$filterjobtype 
										,$filterjobcategory
										,$sortby,$limit,$limitstart)
	{

		if(!$cmbfiltercountry) $cmbfiltercountry = $txtfiltercountry;
		if(!$cmbfilterstate) $cmbfilterstate = $txtfilterstate;
		if(!$cmbfiltercounty) $cmbfiltercounty = $txtfiltercounty;
		if(!$cmbfiltercity) $cmbfiltercity = $txtfiltercity;

		$db = &$this->getDBO();
		$result = array();
		if (is_numeric($companyid) == false) return false;
		if ($filterjobcategory != '') if (is_numeric($filterjobcategory) == false) return false;
		if ($filterjobtype != '') if (is_numeric($filterjobtype) == false) return false;
		if ($filterjobsalaryrange != '') if (is_numeric($filterjobsalaryrange) == false) return false;
		if ($filterheighesteducation != '') if (is_numeric($filterheighesteducation) == false) return false;

		if(! isset($this->_config)){
			$this->getConfig('');
		}	
		foreach ($this->_config as $conf){
			if ($conf->configname == 'filter_address_fields_width')
				$address_fields_width = $conf->configvalue;
		}
		$wherequery = '';
		if ($cmbfiltercountry != '') $wherequery .= " AND job.country = ".$db->Quote($cmbfiltercountry);
		elseif ($txtfiltercountry != '') $wherequery .= " AND country.name LIKE ".$db->Quote($txtfiltercountry);
		if ($cmbfilterstate != '') $wherequery .= " AND job.state = ".$db->Quote($cmbfilterstate);
		elseif ($txtfilterstate != '') $wherequery .= " AND state.name LIKE ".$db->Quote($txtfilterstate);
		if ($cmbfiltercounty != '') $wherequery .= " AND job.county = ".$db->Quote($cmbfiltercounty);
		elseif ($txtfiltercounty != '') $wherequery .= " AND county.name LIKE ".$db->Quote($txtfiltercounty);
		if ($cmbfiltercity != '') $wherequery .= " AND job.city = ".$db->Quote($cmbfiltercity);
		elseif ($txtfiltercity != '') $wherequery .= " AND city.name LIKE ".$db->Quote($txtfiltercity);

		if ($filterjobcategory != '') $wherequery .= " AND job.jobcategory = ".$filterjobcategory;
		if ($filterjobtype != '') $wherequery .= " AND job.jobtype = ".$filterjobtype;
		if ($filterjobsalaryrange != '') $wherequery .= " AND job.jobsalaryrange = ".$filterjobsalaryrange;
		if ($filterheighesteducation != '') $wherequery .= " AND job.heighestfinisheducation = ".$filterheighesteducation;

		$curdate = date('Y-m-d H:i:s');

		$query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code 
				WHERE job.jobcategory = cat.id AND job.status = 1  AND job.companyid = ".$companyid ." 
				AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
                $query .= $wherequery;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		//$limit = $limit ? $limit : 5;
                if ( $total <= $limitstart ) $limitstart = 0;
		
		$query = "SELECT job.*, cat.cat_title, company.name AS companyname, company.url, jobtype.title AS jobtype, jobstatus.title AS jobstatus
					, salary.rangestart, salary.rangeend, country.name AS countryname
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code 
				WHERE job.status = 1 AND job.companyid = ".$companyid ." 
				AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
			
		$query .= $wherequery." ORDER BY  ".$sortby;
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$jobtype = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
		$jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));
		$heighesteducation = $this->getHeighestEducation(JText::_('JS_SELECT_EDUCATION'));

		$job_categories = $this->getCategories(JText::_('JS_SELECT_CATEGORY'));
		$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SELECT_SALARY'));
		$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
		if($cmbfiltercountry != '') $states = $this->getStates($cmbfiltercountry, JText::_('JS_SELECT_STATE'));
		if ($cmbfilterstate != '') $counties = $this->getCounties($cmbfilterstate, JText::_('JS_SELECT_COUNTY'));
		if ($cmbfiltercounty != '') $cities = $this->getCities($cmbfiltercounty, JText::_('JS_SELECT_CITY'));
		
		
		$filterlists['country'] = JHTML::_('select.genericList', $countries, 'cmbfilter_country','class="inputbox"  style="width:'.$address_fields_width.'px;" '.'onChange="filter_dochange(\'filter_state\', this.value)"', 'value', 'text', $cmbfiltercountry);
		if ( isset($states[1]) ) if ($states[1] != '') $filterlists['state'] = JHTML::_('select.genericList', $states, 'cmbfilter_state', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_county\', this.value)"', 'value', 'text', $cmbfilterstate);
		if ( isset($counties[1]) ) if ($counties[1] != '') $filterlists['county'] = JHTML::_('select.genericList', $counties, 'cmbfilter_county', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_city\', this.value)"', 'value', 'text', $cmbfiltercounty);
		if ( isset($cities[1]) ) if ($cities[1] != '') $filterlists['city'] = JHTML::_('select.genericList', $cities, 'cmbfilter_city', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. '', 'value', 'text', $cmbfiltercity);

		$filterlists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'filter_jobcategory', 'class="inputbox" '. '', 'value', 'text', $filterjobcategory);
		$filterlists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'filter_jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', $filterjobsalaryrange);
		$filterlists['jobtype'] = JHTML::_('select.genericList', $jobtype, 'filter_jobtype', 'class="inputbox" '. '', 'value', 'text', $filterjobtype);
		$filterlists['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'filter_heighesteducation', 'class="inputbox" '. '', 'value', 'text', $filterheighesteducation);

		$filtervalues['state'] = $txtfilterstate;
		$filtervalues['county'] = $txtfiltercounty;
		$filtervalues['city'] = $txtfiltercity;
		
		$result[0] = $this->_applications;
		$result[1] = $total;
		$result[2] = $filterlists;
		$result[3] = $filtervalues;
		
		return $result;
	}

        function &getActiveJobsByCompany($companyid,$cmbfiltercountry,$cmbfilterstate,$cmbfiltercounty,$cmbfiltercity
											,$txtfiltercountry,$txtfilterstate,$txtfiltercounty,$txtfiltercity
											,$filterjobsalaryrange,$filterheighesteducation,$filterjobcategory,$filterjobtype,$sortby
											 ,$limit,$limitstart)
	{
		$db = &$this->getDBO();
		$result = array();
		if (is_numeric($companyid) == false) return false;
		if ($filterjobcategory != '') if (is_numeric($filterjobcategory) == false) return false;
		if ($filterjobtype != '') if (is_numeric($filterjobtype) == false) return false;
		if ($filterjobsalaryrange != '') if (is_numeric($filterjobsalaryrange) == false) return false;
		if ($filterheighesteducation != '') if (is_numeric($filterheighesteducation) == false) return false;


		if(!$cmbfiltercountry) $cmbfiltercountry = $txtfiltercountry;
		if(!$cmbfilterstate) $cmbfilterstate = $txtfilterstate;
		if(!$cmbfiltercounty) $cmbfiltercounty = $txtfiltercounty;
		if(!$cmbfiltercity) $cmbfiltercity = $txtfiltercity;
		
		if(! isset($this->_config)){
			$this->getConfig('');
		}	
		foreach ($this->_config as $conf){
			if ($conf->configname == 'filter_address_fields_width')
				$address_fields_width = $conf->configvalue;
		}
		$listjobconfig=$this->getConfigByFor('listjob');

		$wherequery = '';
		if ($cmbfiltercountry != '') $wherequery .= " AND job.country = ".$db->Quote($cmbfiltercountry);
		elseif ($txtfiltercountry != '') $wherequery .= " AND country.name LIKE ".$db->Quote($txtfiltercountry);
		if ($cmbfilterstate != '') $wherequery .= " AND job.state = ".$db->Quote($cmbfilterstate);
		elseif ($txtfilterstate != '') $wherequery .= " AND state.name LIKE ".$db->Quote($txtfilterstate);
		if ($cmbfiltercounty != '') $wherequery .= " AND job.county = ".$db->Quote($cmbfiltercounty);
		elseif ($txtfiltercounty != '') $wherequery .= " AND county.name LIKE ".$db->Quote($txtfiltercounty);
		if ($cmbfiltercity != '') $wherequery .= " AND job.city = ".$db->Quote($cmbfiltercity);
		elseif ($txtfiltercity != '') $wherequery .= " AND city.name LIKE ".$db->Quote($txtfiltercity);

		if ($filterjobcategory != '') $wherequery .= " AND job.jobcategory = ".$filterjobcategory;
		if ($filterjobtype != '') $wherequery .= " AND job.jobtype = ".$filterjobtype;
		if ($filterjobsalaryrange != '') $wherequery .= " AND job.jobsalaryrange = ".$filterjobsalaryrange;
		if ($filterheighesteducation != '') $wherequery .= " AND job.heighestfinisheducation = ".$filterheighesteducation;

		$curdate = date('Y-m-d H:i:s');

                $query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code 
				WHERE job.jobcategory = cat.id AND job.status = 1  AND job.companyid = ".$companyid ." 
				AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
                $query .= $wherequery;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		//$limit = $limit ? $limit : 5;
                if ( $total <= $limitstart ) $limitstart = 0;
		
		$query = "SELECT job.*, cat.cat_title, company.name AS companyname, company.url, jobtype.title AS jobtype, jobstatus.title AS jobstatus
					, salary.rangestart, salary.rangeend, country.name AS countryname
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code 
				WHERE job.jobcategory = cat.id AND job.status = 1  AND job.companyid = ".$companyid ." 
				AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
				
			
		$query .= $wherequery." ORDER BY  ".$sortby;
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$jobtype = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
		$jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));
		$heighesteducation = $this->getHeighestEducation(JText::_('JS_SELECT_EDUCATION'));

		$job_categories = $this->getCategories(JText::_('JS_SELECT_CATEGORY'));
		$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SELECT_SALARY'));
		$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
		if($cmbfiltercountry != '') $states = $this->getStates($cmbfiltercountry, JText::_('JS_SELECT_STATE'));
		if ($cmbfilterstate != '') $counties = $this->getCounties($cmbfilterstate, JText::_('JS_SELECT_COUNTY'));
		if ($cmbfiltercounty != '') $cities = $this->getCities($cmbfiltercounty, JText::_('JS_SELECT_CITY'));
		
		
		$filterlists['country'] = JHTML::_('select.genericList', $countries, 'cmbfilter_country','class="inputbox"  style="width:'.$address_fields_width.'px;" '.'onChange="filter_dochange(\'filter_state\', this.value)"', 'value', 'text', $cmbfiltercountry);
		if ( isset($states[1]) ) if ($states[1] != '') $filterlists['state'] = JHTML::_('select.genericList', $states, 'cmbfilter_state', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_county\', this.value)"', 'value', 'text', $cmbfilterstate);
		if ( isset($counties[1]) ) if ($counties[1] != '') $filterlists['county'] = JHTML::_('select.genericList', $counties, 'cmbfilter_county', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_city\', this.value)"', 'value', 'text', $cmbfiltercounty);
		if ( isset($cities[1]) ) if ($cities[1] != '') $filterlists['city'] = JHTML::_('select.genericList', $cities, 'cmbfilter_city', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. '', 'value', 'text', $cmbfiltercity);

		$filterlists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'filter_jobcategory', 'class="inputbox" '. '', 'value', 'text', $filterjobcategory);
		$filterlists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'filter_jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', $filterjobsalaryrange);
		$filterlists['jobtype'] = JHTML::_('select.genericList', $jobtype, 'filter_jobtype', 'class="inputbox" '. '', 'value', 'text', $filterjobtype);
		$filterlists['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'filter_heighesteducation', 'class="inputbox" '. '', 'value', 'text', $filterheighesteducation);

		$filtervalues['state'] = $txtfilterstate;
		$filtervalues['county'] = $txtfiltercounty;
		$filtervalues['city'] = $txtfiltercity;
		
                $packageexpiry = $this->getJobSeekerPackageExpiry(null);
                if($packageexpiry == 1){ //package expire or user not login
                    $listjobconfigs = array();
                    $listjobconfigs['lj_title'] = $listjobconfig['visitor_lj_title'];
                    $listjobconfigs['lj_category'] = $listjobconfig['visitor_lj_category'];
                    $listjobconfigs['lj_jobtype'] = $listjobconfig['visitor_lj_jobtype'];
                    $listjobconfigs['lj_jobstatus'] = $listjobconfig['visitor_lj_jobstatus'];
                    $listjobconfigs['lj_company'] = $listjobconfig['visitor_lj_company'];
                    $listjobconfigs['lj_companysite'] = $listjobconfig['visitor_lj_companysite'];
                    $listjobconfigs['lj_country'] = $listjobconfig['visitor_lj_country'];
                    $listjobconfigs['lj_state'] = $listjobconfig['visitor_lj_state'];
                    $listjobconfigs['lj_county'] = $listjobconfig['visitor_lj_county'];
                    $listjobconfigs['lj_city'] = $listjobconfig['visitor_lj_city'];
                    $listjobconfigs['lj_salary'] = $listjobconfig['visitor_lj_salary'];
                    $listjobconfigs['lj_created'] = $listjobconfig['visitor_lj_created'];
                    $listjobconfigs['lj_noofjobs'] = $listjobconfig['visitor_lj_noofjobs'];
                }else $listjobconfigs = $listjobconfig; // user

                $result[0] = $this->_applications;
		$result[1] = $total;
		$result[2] = $filterlists;
		$result[3] = $filtervalues;
		$result[4]=$listjobconfigs;
		
		return $result;
	}

	function &getCompanybyId($companyid)
	{
		$db = &$this->getDBO();
		if (is_numeric($companyid) == false) return false;
		$query = "SELECT company.*, cat.cat_title, country.name AS countryname, state.name AS statename
					, county.name AS countyname, city.name AS cityname
		FROM ".$db->nameQuote('#__wrecruit_companies')." AS company
		JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON company.category = cat.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON company.country = country.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON company.state = state.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON company.county = county.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON company.city = city.code
		WHERE  company.id = " . $companyid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$result[0] = $db->loadObject();

		$query = "UPDATE ".$db->nameQuote('#__wrecruit_companies')." SET hits = hits+1 WHERE id = ".$companyid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			//return false;
		}
		$result[2] = $this->getUserFieldsForView(1, $companyid); // company fields, id
		$result[3] = $this->getFieldsOrdering(1); // company fields
		return $result;
	}

	function &getListNewestJobs($uid, $cmbfiltercountry,$cmbfilterstate,$cmbfiltercounty,$cmbfiltercity
											,$txtfiltercountry,$txtfilterstate,$txtfiltercounty,$txtfiltercity
											,$filterjobsalaryrange,$filterheighesteducation,$filterjobcategory,$filterjobtype
											,$limit,$limitstart){
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if ($filterjobtype != '') if (is_numeric($filterjobtype) == false) return false;
		if ($filterjobsalaryrange != '') if (is_numeric($filterjobsalaryrange) == false) return false;
		if ($filterheighesteducation != '') if (is_numeric($filterheighesteducation) == false) return false;
		if ($filterjobcategory != '') if (is_numeric($filterjobcategory) == false) return false;

		if(!$cmbfiltercountry) $cmbfiltercountry = $txtfiltercountry;
		if(!$cmbfilterstate) $cmbfilterstate = $txtfilterstate;
		if(!$cmbfiltercounty) $cmbfiltercounty = $txtfiltercounty;
		if(!$cmbfiltercity) $cmbfiltercity = $txtfiltercity;

        $db = &$this->getDBO();
		$result = array();
		if(! isset($this->_config)){
			$this->getConfig('');
		}	
		foreach ($this->_config as $conf){
			if ($conf->configname == 'filter_address_fields_width')
				$address_fields_width = $conf->configvalue;
			if ($conf->configname == 'defaultcountry')
				$defaultcountry = $conf->configvalue;
			if ($conf->configname == 'hidecountry')
				$hidecountry = $conf->configvalue;
		}
		//if(!$defaultcountry) $defaultcountry = 'PK';
		//if(!$cmbfiltercountry) $cmbfiltercountry = $defaultcountry;
		$listjobconfig = $this->getConfigByFor('listjob');
		
		$wherequery = '';
		if ($cmbfiltercountry != '') $wherequery .= " AND job.country = ".$db->Quote($cmbfiltercountry);
		elseif ($txtfiltercountry != '') $wherequery .= " AND country.name LIKE ".$db->Quote($txtfiltercountry);
		if ($cmbfilterstate != '') $wherequery .= " AND job.state = ".$db->Quote($cmbfilterstate);
		elseif ($txtfilterstate != '') $wherequery .= " AND state.name LIKE ".$db->Quote($txtfilterstate);
		if ($cmbfiltercounty != '') $wherequery .= " AND job.county = ".$db->Quote($cmbfiltercounty);
		elseif ($txtfiltercounty != '') $wherequery .= " AND county.name LIKE ".$db->Quote($txtfiltercounty);
		if ($cmbfiltercity != '') $wherequery .= " AND job.city = ".$db->Quote($cmbfiltercity);
		elseif ($txtfiltercity != '') $wherequery .= " AND city.name LIKE ".$db->Quote($txtfiltercity);
		
		if ($filterjobtype != '') $wherequery .= " AND job.jobtype = ".$filterjobtype;
		if ($filterjobsalaryrange != '') $wherequery .= " AND job.jobsalaryrange = ".$filterjobsalaryrange;
		if ($filterheighesteducation != '') $wherequery .= " AND job.heighestfinisheducation = ".$filterheighesteducation;
		if ($filterjobcategory != '') $wherequery .= " AND job.jobcategory = ".$filterjobcategory;
		
		$curdate = date('Y-m-d H:i:s');

		$query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code 
				WHERE job.jobcategory = cat.id AND job.status = 1 AND (job.jobstatus BETWEEN 1 AND 5) 
				AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
		$query .= $wherequery;
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT job.*, cat.cat_title, jobtype.title AS jobtype, jobstatus.title AS jobstatus
					, company.id AS companyid, company.name AS companyname, company.url 
					, salaryfrom.rangestart AS salaryfrom, salaryto.rangeend AS salaryto, salarytype.title AS salaytype
					, country.name AS countryname,city.name AS cityname,county.name AS countyname,state.name AS statename , currency.symbol
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryfrom ON job.salaryrangefrom = salaryfrom.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryto ON job.salaryrangeto = salaryto.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrangetypes')." AS salarytype ON job.salaryrangetype = salarytype.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON job.currencyid = currency.id 
				WHERE job.status = 1  
				AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
				
		$query .= $wherequery." ORDER BY  job.startpublishing DESC";
                //echo $query;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$jobtype = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
		$jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));
		$heighesteducation = $this->getHeighestEducation(JText::_('JS_SELECT_EDUCATION'));

		$job_categories = $this->getCategories(JText::_('JS_SELECT_CATEGORY'));
		$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SELECT_SALARY'));
		if($hidecountry != 1)$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
		if($cmbfiltercountry != '') $states = $this->getStates($cmbfiltercountry, JText::_('JS_SELECT_STATE'));
		if ($cmbfilterstate != '') $counties = $this->getCounties($cmbfilterstate, JText::_('JS_SELECT_COUNTY'));
		if ($cmbfiltercounty != '') $cities = $this->getCities($cmbfiltercounty, JText::_('JS_SELECT_CITY'));
		
		
		if($hidecountry != 1)$filterlists['country'] = JHTML::_('select.genericList', $countries, 'cmbfilter_country','class="inputbox"  style="width:'.$address_fields_width.'px;" '.'onChange="filter_dochange(\'filter_state\', this.value)"', 'value', 'text', $cmbfiltercountry);
		if ( isset($states[1]) ) if ($states[1] != '') $filterlists['state'] = JHTML::_('select.genericList', $states, 'cmbfilter_state', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_county\', this.value)"', 'value', 'text', $cmbfilterstate);
		if ( isset($counties[1]) ) if ($counties[1] != '') $filterlists['county'] = JHTML::_('select.genericList', $counties, 'cmbfilter_county', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. 'onChange="filter_dochange(\'filter_city\', this.value)"', 'value', 'text', $cmbfiltercounty);
		if ( isset($cities[1]) ) if ($cities[1] != '') $filterlists['city'] = JHTML::_('select.genericList', $cities, 'cmbfilter_city', 'class="inputbox"  style="width:'.$address_fields_width.'px;" '. '', 'value', 'text', $cmbfiltercity);

		$filterlists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'filter_jobcategory', 'class="inputbox" '. '', 'value', 'text', $filterjobcategory);
		$filterlists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'filter_jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', $filterjobsalaryrange);
		$filterlists['jobtype'] = JHTML::_('select.genericList', $jobtype, 'filter_jobtype', 'class="inputbox" '. '', 'value', 'text', $filterjobtype);
		$filterlists['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'filter_heighesteducation', 'class="inputbox" '. '', 'value', 'text', $filterheighesteducation);

		$filtervalues['state'] = $txtfilterstate;
		$filtervalues['county'] = $txtfiltercounty;
		$filtervalues['city'] = $txtfiltercity;
		
                $packageexpiry = $this->getJobSeekerPackageExpiry($uid);
                if($packageexpiry == 1){ //package expire or user not login
                    $listjobconfigs = array();
                    $listjobconfigs['lj_title'] = $listjobconfig['visitor_lj_title'];
                    $listjobconfigs['lj_category'] = $listjobconfig['visitor_lj_category'];
                    $listjobconfigs['lj_jobtype'] = $listjobconfig['visitor_lj_jobtype'];
                    $listjobconfigs['lj_jobstatus'] = $listjobconfig['visitor_lj_jobstatus'];
                    $listjobconfigs['lj_company'] = $listjobconfig['visitor_lj_company'];
                    $listjobconfigs['lj_companysite'] = $listjobconfig['visitor_lj_companysite'];
                    $listjobconfigs['lj_country'] = $listjobconfig['visitor_lj_country'];
                    $listjobconfigs['lj_state'] = $listjobconfig['visitor_lj_state'];
                    $listjobconfigs['lj_county'] = $listjobconfig['visitor_lj_county'];
                    $listjobconfigs['lj_city'] = $listjobconfig['visitor_lj_city'];
                    $listjobconfigs['lj_salary'] = $listjobconfig['visitor_lj_salary'];
                    $listjobconfigs['lj_created'] = $listjobconfig['visitor_lj_created'];
                    $listjobconfigs['lj_noofjobs'] = $listjobconfig['visitor_lj_noofjobs'];
                    $listjobconfigs['lj_description'] = $listjobconfig['visitor_lj_description'];
                    $listjobconfigs['lj_shortdescriptionlenght'] = $listjobconfig['lj_shortdescriptionlenght'];
                    $listjobconfigs['lj_joblistingstyle'] = $listjobconfig['lj_joblistingstyle'];
                }else $listjobconfigs = $listjobconfig; // user

                $result[0] = $this->_applications;
		$result[1] = $total;
		$result[2] = $filterlists;
		$result[3] = $filtervalues;
		$result[4] = $listjobconfigs;

		return $result;
	}
	
	function getEmployerPackageExpiry($uid)
        {
                $db = &$this->getDBO();
                if (($uid == 0) || ($uid == '')) return 1;
		$query = "SELECT package.id 
                        FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
                        JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
                        WHERE payment.uid = ".$uid."
                        AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                        AND payment.transactionverified = 1 AND payment.status = 1";
		//echo $query;
		$db->setQuery($query);
		$packages = $db->loadObjectList();
                if (isset($packages)) return 0; else return 1;
            
        }

        function getJobSeekerPackageExpiry($uid)
        {
                $db = &$this->getDBO();
                if (($uid == 0) || ($uid == '')) return 1;
		$query = "SELECT package.id
		FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid."
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
		AND payment.transactionverified = 1 AND payment.status = 1";
		//echo $query;
		$db->setQuery($query);
		$packages = $db->loadObjectList();
                if (isset($packages)) return 0; else return 1;

        }

        function &getJobbyId($job_id)
	{
		$db = &$this->getDBO();
		if (is_numeric($job_id) == false) return false;

                $query = "SELECT job.*, cat.cat_title, subcat.title as subcategory, company.name as companyname, jobtype.title AS jobtypetitle
				, jobstatus.title AS jobstatustitle, shift.title as shifttitle
				, department.name AS departmentname
				, salaryfrom.rangestart AS salaryfrom, salaryto.rangestart AS salaryto, salarytype.title AS salarytype
				, education.title AS educationtitle ,mineducation.title AS mineducationtitle, maxeducation.title AS maxeducationtitle
				, experience.title AS experiencetitle ,minexperience.title AS minexperiencetitle, maxexperience.title AS maxexperiencetitle
				, country.name AS countryname, state.name AS statename, county.name AS countyname, city.name AS cityname
				, currency.symbol
		FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
		JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_subcategories')." AS subcat ON job.subcategoryid = subcat.id
		JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
		JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
		JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_departments')." AS department ON job.departmentid = department.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryfrom ON job.salaryrangefrom = salaryfrom.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryto ON job.salaryrangeto = salaryto.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrangetypes')." AS salarytype ON job.salaryrangetype = salarytype.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS education ON job.educationid = education.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS mineducation ON job.mineducationrange = mineducation.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS maxeducation ON job.maxeducationrange = maxeducation.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_experiences')." AS experience ON job.experienceid = experience.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_experiences')." AS minexperience ON job.minexperiencerange = minexperience.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_experiences')." AS maxexperience ON job.maxexperiencerange = maxexperience.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_shifts')." AS shift ON job.shift = shift.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')."AS currency ON currency.id = job.currencyid
		WHERE  job.id = " . $job_id;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$this->_application = $db->loadObject();

		$query = "UPDATE ".$db->nameQuote('#__wrecruit_jobs')." SET hits = hits + 1 WHERE id = ".$job_id;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			//return false;
		}

		$result[0] = $this->_application;
		$result[2] = $this->getUserFieldsForView(2, $job_id); // company fields, id
		$result[3] = $this->getFieldsOrdering(2); // company fields
		$result[4] = $this->getConfigByFor('listjob'); // company fields
		//$result[4]=$canviewmap;
		//$result[5]=$canviewvideo;
		return $result;
	}

	function &getJobbyIdforJobApply($job_id)
	{
		$db = &$this->getDBO();
		
		if (is_numeric($job_id) == false) return false;
		$query = "SELECT job.*, cat.cat_title , company.name as companyname, company.url
				, jobtype.title AS jobtypetitle
				, jobstatus.title AS jobstatustitle, shift.title as shifttitle
				, salary.rangestart, salary.rangeend, education.title AS heighesteducationtitle
				, country.name AS countryname, state.name AS statename, county.name AS countyname, city.name AS cityname
		FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
		JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
		JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
		JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
		JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS education ON job.heighestfinisheducation = education.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_shifts')." AS shift ON job.shift = shift.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
		WHERE  job.id = " . $job_id;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$this->_application = $db->loadObject();
		$result[0] = $this->_application;
		return $result;
	}

	function &getMyResumes($u_id)
	{
		
		$db = &$this->getDBO();
		if($u_id) if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		
		$totalresume = 0;

		$query = "SELECT id, application_title, create_date, status 
		FROM ".$db->nameQuote('#__wrecruit_resume')."	WHERE status = 1 AND uid = ".$u_id;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$resumes = array();
		foreach($rows as $row)	{
			$resumes[] =  array('value' => $row->id, 'text' => $row->application_title);
			$totalresume++;
		}
		
		$myresymes = JHTML::_('select.genericList', $resumes, 'cvid', 'class="inputbox required" '. '', 'value', 'text', '');
		
		$result[0] = $myresymes;
		$result[1] = $totalresume;
		return $result;
	}

	function &getMyAppliedJobs($u_id,$sortby,$limit,$limitstart)
	{
		$db = &$this->getDBO();
		if($u_id) if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		$result = array();
		$listjobconfig = $this->getConfigByFor('listjob');

		$query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job, ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  
		WHERE apply.jobid = job.id AND apply.uid = ".$u_id;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT job.*, cat.cat_title, apply.apply_date, jobtype.title AS jobtypetitle, jobstatus.title AS jobstatustitle
				, salary.rangestart, salary.rangeend, country.name AS countryname
				, company.name AS companyname, company.url,salarytype.title AS salaytype,
                                state.name AS statename, county.name AS countyname, city.name AS cityname
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id 
				JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrangetypes')." AS salarytype ON job.salaryrangetype = salarytype.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
				, ".$db->nameQuote('#__wrecruit_categories')." AS cat
				, ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  
		WHERE job.jobcategory = cat.id AND apply.jobid = job.id AND apply.uid = ".$u_id." ORDER BY  ".$sortby;
                //echo '<br>'.$query;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$result[0] = $this->_applications;
		$result[1] = $total;
		$result[2] = $listjobconfig;
		
		return $result;
	}

	function &getJobsAppliedResume($u_id,$sortby,$limit,$limitstart)
	{
		$db = &$this->getDBO();
		if($u_id) if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		$result = array();

		$query = "SELECT COUNT(job.id)
		FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job, ".$db->nameQuote('#__wrecruit_categories')." AS cat 
		WHERE job.jobcategory = cat.id AND job.uid= ".$u_id;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		//$limit = $limit ? $limit : 5;
                if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT DISTINCT job.*, cat.cat_title , company.name ,jobtype.title AS jobtypetitle, jobstatus.title AS jobstatustitle
				, (SELECT COUNT(apply.id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply WHERE apply.jobid = job.id ) as appinjob
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
				JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
			WHERE job.uid= ".$u_id." ORDER BY  ".$sortby;
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$result[0] = $this->_applications;
		$result[1] = $total;
		
		return $result;
	}
	function &getShortListCandidate($jobid,$sortby,$limit,$limitstart)
	{
		$db = &$this->getDBO();
		if (is_numeric($jobid) == false) return false;
		$result = array();
		$query = "SELECT COUNT(job.id)
		FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job 
		JOIN ".$db->nameQuote('#__wrecruit_shortlistcandidates')." AS candidate ON job.id=candidate.jobid  
		JOIN ".$db->nameQuote('#__wrecruit_resume')." AS resume ON candidate.cvid = resume.id 
		WHERE  job.id=".$jobid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;
		/*$query ="SELECT job.id, resume.id AS resumeid, job.title,resume.first_name as firstname,resume.last_name as lastname,candidate.created
			 , (SELECT COUNT(apply.id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply WHERE apply.jobid =". $jobid.") as appliedjob
		FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job 
		JOIN ".$db->nameQuote('#__wrecruit_shortlistcandidates')." AS candidate ON job.id=candidate.jobid  
		JOIN ".$db->nameQuote('#__wrecruit_resume')." AS resume ON candidate.cvid = resume.id 
		WHERE  job.id=".$jobid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();
		$result[0] = $this->_applications;
		$result[1] = $total;
		return $result;*/
		$query = "SELECT apply.comments,apply.id AS jobapplyid ,job.id,job.agefrom,job.ageto, 
		cat.cat_title ,apply.apply_date, apply.resumeview, jobtype.title AS jobtypetitle,
				app.iamavailable, app.id AS appid, app.first_name, app.last_name, app.email_address, 
				app.jobtype,app.gender	,app.total_experience, app.jobsalaryrange,rating.id AS ratingid, rating.rating
				,app.address_city, app.address_county, app.address_state
				,country.name AS countryname,state.name AS statename
				,county.name AS countyname,city.name AS cityname
				, salary.rangestart, salary.rangeend,education.title AS educationtitle
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_shortlistcandidates')." AS candidate ON job.id=candidate.jobid
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  ON candidate.cvid = apply.cvid AND candidate.jobid = apply.jobid
				JOIN ".$db->nameQuote('#__wrecruit_resume')." AS app ON apply.cvid = app.id
				LEFT JOIN  ".$db->nameQuote('#__wrecruit_resumerating')." AS rating ON (app.id=rating.resumeid AND apply.jobid=rating.jobid)
				LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS  education  ON app.heighestfinisheducation=education.id
				LEFT JOIN  ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary	ON	app.jobsalaryrange=salary.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON app.address_country  = country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON app.address_state = state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON app.address_county  = county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON app.address_city = city.code

		WHERE apply.jobid = ".$jobid." ORDER BY  ".$sortby;
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$result[0] = $this->_applications;
		$result[1] = $total;

		return $result;


        }
	function &getMessagesbyJobs($uid,$limit,$limitstart)
	{
		$result = array();
		$db = &$this->getDBO();

		if (is_numeric($uid) == false) return false;
		if (($uid == 0) || ($uid == '')) return false;
		$total=0;
                $query = "SELECT message.id
                            FROM ".$db->nameQuote('#__wrecruit_messages')." as message
                            JOIN ".$db->nameQuote('#__wrecruit_jobs')." as job ON job.id = message.jobid
                            JOIN ".$db->nameQuote('#__wrecruit_companies')." as company ON company.id = job.companyid
                            WHERE message.employerid = ".$uid."
                            GROUP BY message.jobid
                            ";
		$db->setQuery($query);
		$totobj = $db->loadObjectList();
		foreach ($totobj as $obj) $total++;

		if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT message.id, message.jobid, job.title, job.created, company.id as companyid, company.name as companyname
                            ,(SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_messages')." WHERE employerid = ".$uid." AND sendby != ".$uid." AND isread = 0) as unread
                            FROM ".$db->nameQuote('#__wrecruit_messages')." as message
                            JOIN ".$db->nameQuote('#__wrecruit_jobs')." as job ON job.id = message.jobid
                            JOIN ".$db->nameQuote('#__wrecruit_companies')." as company ON company.id = job.companyid
                            WHERE message.employerid = ".$uid."
                            GROUP BY message.jobid
                            ORDER BY message.created DESC ";
               // echo $query;
		$db->setQuery($query, $limitstart, $limit);
		$messages = $db->loadObjectList();
		$result[0] = $messages;
		$result[1] = $total;

		return $result;
	}
	function &getMessagesbyJob($uid,$jobid,$limit,$limitstart)
	{
		$result = array();
		$db = &$this->getDBO();

		if (is_numeric($uid) == false) return false;
		if (($uid == 0) || ($uid == '')) return false;
                $query = "SELECT count(message.id)
                        FROM ".$db->nameQuote('#__wrecruit_messages')." as message
                        JOIN ".$db->nameQuote('#__wrecruit_jobs')." as job ON job.id = message.jobid
                        JOIN ".$db->nameQuote('#__wrecruit_resume')." as resume ON resume.id = message.resumeid
                        WHERE message.employerid = ".$uid." AND message.jobid = ".$jobid."
                        GROUP BY message.jobseekerid";
		$db->setQuery($query);
                //echo $query;
		$msgs = $db->loadObjectList();
                $total = 0;
                foreach ($msgs AS $msg) $total ++;
		if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT message.id, message.jobid, message.resumeid, job.title, job.created, resume.id as resumeidid, resume.application_title, resume.first_name, resume.middle_name, resume.last_name
                        ,(SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_messages')." WHERE employerid=".$uid." AND message.jobid = ".$jobid." AND sendby != ".$uid." AND isread = 0 AND resume.id = resumeid) as unread
                        FROM ".$db->nameQuote('#__wrecruit_messages')." as message
                        JOIN ".$db->nameQuote('#__wrecruit_jobs')." as job ON job.id = message.jobid
                        JOIN ".$db->nameQuote('#__wrecruit_resume')." as resume ON resume.id = message.resumeid
                        WHERE message.employerid = ".$uid." AND message.jobid = ".$jobid."
                        GROUP BY message.jobseekerid
                        ORDER BY message.created DESC ";
                //echo $query;
		$db->setQuery($query, $limitstart, $limit);
		$messages = $db->loadObjectList();
		$result[0] = $messages;
		$result[1] = $total;

		return $result;
	}
	function &getMessagesbyJobsforJobSeeker($uid,$limit,$limitstart)
	{
		$result = array();
		$db = &$this->getDBO();

		if (is_numeric($uid) == false) return false;
		if (($uid == 0) || ($uid == '')) return false;
		$total = 0;
			   $query = "SELECT message.id
                            FROM ".$db->nameQuote('#__wrecruit_messages')." as message
                            JOIN ".$db->nameQuote('#__wrecruit_jobs')." as job ON job.id = message.jobid
                            JOIN ".$db->nameQuote('#__wrecruit_companies')." as company ON company.id = job.companyid
                            WHERE message.jobseekerid = ".$uid."
                            GROUP BY message.jobid";
		$db->setQuery($query);
		$totobj = $db->loadObjectList();
		foreach ($totobj as $obj) $total++;

		if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT message.id, message.jobid, message.resumeid, job.title, job.created, company.id as companyid, company.name as companyname
                            ,(SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_messages')." WHERE jobseekerid = ".$uid." AND sendby != ".$uid." AND jobid = message.jobid AND isread = 0) as unread
                            FROM ".$db->nameQuote('#__wrecruit_messages')." as message
                            JOIN ".$db->nameQuote('#__wrecruit_jobs')." as job ON job.id = message.jobid
                            JOIN ".$db->nameQuote('#__wrecruit_companies')." as company ON company.id = job.companyid
                            WHERE message.jobseekerid = ".$uid."
                            GROUP BY message.jobid
                            ORDER BY message.created DESC ";
               // echo $query;
		$db->setQuery($query, $limitstart, $limit);
		$messages = $db->loadObjectList();
		$result[0] = $messages;
		$result[1] = $total;

		return $result;
	}
	function &getMessagesbyJobResume($uid,$jobid,$resumeid,$limit,$limitstart)
	{
		$result = array();
		$db = &$this->getDBO();

		if (is_numeric($uid) == false) return false;
		if (($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($resumeid) == false) return false;
		$listjobconfig = $this->getConfigByFor('listjob');
		$query = "SELECT count(message.id)
                        FROM ".$db->nameQuote('#__wrecruit_messages')." AS message
                        WHERE message.status = 1 AND message.jobid =".$jobid." AND message.resumeid = ".$resumeid;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT message.*, job.title, resume.application_title, resume.first_name, resume.middle_name, resume.last_name
                        FROM ".$db->nameQuote('#__wrecruit_messages')." AS message
                                JOIN ".$db->nameQuote('#__wrecruit_jobs')." AS job ON job.id = message.jobid
				JOIN ".$db->nameQuote('#__wrecruit_resume')." AS resume ON resume.id = message.resumeid
                        WHERE message.status = 1 AND message.jobid =".$jobid." AND message.resumeid = ".$resumeid." ORDER BY  message.created DESC";
                //echo $query;
		$db->setQuery($query, $limitstart, $limit);
		$messages = $db->loadObjectList();
                if ($total > 0) $canadd = true;
                else $canadd = $this->canAddMessage($uid);
                if ($canadd){
                    $query = "SELECT job.id as jobid, job.uid as employerid, job.title, resume.id as resumeid, resume.uid as jobseekerid, resume.application_title, resume.first_name, resume.middle_name, resume.last_name
                                    FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
                                    JOIN ".$db->nameQuote('#__wrecruit_resume')." AS resume ON resume.id = ".$resumeid."
                                    WHERE job.id = ".$jobid;
               // echo $query;
                    $db->setQuery($query);
                    $summary = $db->loadObject();
                }
		$result[0] = $messages;
		$result[1] = $total;
		$result[2] = $canadd;
                if(isset($summary))
                $result[3] = $summary;

		return $result;
	}
	function canAddMessage($uid)
	{
		$db = &$this->getDBO();

                $returnvalue = array();
                $packagedetail = array();
                if (($uid == 0) || ($uid == '')){ return false; }
		$query = "SELECT package.id, package.messageallow, package.packageexpireindays, payment.id AS paymentid, payment.created
		FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid."
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
		AND payment.transactionverified = 1 AND payment.status = 1";
		$db->setQuery($query);
		$packages = $db->loadObjectList();
		$allow = 0;
		foreach($packages AS $package){
			if($allow == 0){
				if ($package->messageallow == 1){
                                    $allow = true;
                                    return true;
                                }
			}
		}
                return $allow;

        }
	function &getJobAppliedResume($u_id,$jobid,$sortby,$limit,$limitstart)
	{
		
		$db = &$this->getDBO();
		if (is_numeric($u_id) == false) return false;
		if (is_numeric($jobid) == false) return false;
		$result = array();
		$query = "SELECT COUNT(job.id)
		FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
		   , ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  
		   , ".$db->nameQuote('#__wrecruit_resume')." AS app  
		   , ".$db->nameQuote('#__wrecruit_currencies')." AS currency  
		   
		WHERE apply.jobid = job.id AND apply.cvid = app.id AND job.currencyid = currency.id AND apply.jobid = ".$jobid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		//$limit = $limit ? $limit : 5;
                if ( $total <= $limitstart ) $limitstart = 0;
		
		$query = "SELECT apply.comments,apply.id AS jobapplyid ,job.id,job.agefrom,job.ageto, cat.cat_title ,apply.apply_date, apply.resumeview, jobtype.title AS jobtypetitle,app.iamavailable
				, app.id AS appid, app.first_name, app.last_name, app.email_address, app.jobtype,app.gender
				, app.total_experience, app.jobsalaryrange,rating.id AS ratingid, rating.rating
				, app.address_city, app.address_county, app.address_state ,app.id as resumeid
				, country.name AS countryname,state.name AS statename
				, county.name AS countyname,city.name AS cityname
				, salary.rangestart, salary.rangeend,education.title AS educationtitle
				, currency.symbol AS symbol 
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  ON apply.jobid = job.id 
				JOIN ".$db->nameQuote('#__wrecruit_resume')." AS app ON apply.cvid = app.id 
				LEFT JOIN  ".$db->nameQuote('#__wrecruit_resumerating')." AS rating ON (app.id=rating.resumeid AND apply.jobid=rating.jobid)
				LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS  education  ON app.heighestfinisheducation=education.id
				LEFT OUTER JOIN  ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary	ON	app.jobsalaryrange=salary.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON app.address_country  = country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON app.address_state = state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON app.address_county  = county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON app.address_city = city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = job.currencyid
				
		WHERE apply.jobid = ".$jobid." ORDER BY  ".$sortby;
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$result[0] = $this->_applications;
		$result[1] = $total;
		
		return $result;
	}

	function &getMyResumesbyUid($u_id,$sortby,$limit,$limitstart)
	{
		$db = &$this->getDBO();
		if (is_numeric($u_id) == false) return false;
		$result = array();
                $resumeconfig = $this->getConfigByFor('searchresume');
		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE uid  = ".$u_id;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		//$limit = $limit ? $limit : 5;
                if ( $total <= $limitstart ) $limitstart = 0;
		
		$query = "SELECT resume.* , category.cat_title, jobtype.title AS jobtypetitle, salary.rangestart, salary.rangeend
					, country.name AS countryname,city.name AS cityname,county.name AS countyname,state.name AS statename
					, currency.symbol		
					FROM ".$db->nameQuote('#__wrecruit_resume')." AS resume
					JOIN  ".$db->nameQuote('#__wrecruit_categories')." AS category ON	resume.job_category = category.id
					JOIN  ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary	ON	resume.jobsalaryrange = salary.id
					JOIN  ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON resume.jobtype = jobtype.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON resume.employer_country = country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON resume.employer_state= state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON resume.employer_county= county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON resume.employer_city= city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id= resume.currencyid
					WHERE resume.uid  = ".$u_id ."
					ORDER BY ". $sortby;
		//echo '<br> sql '.$query;
		$db->setQuery($query);
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$result[0] = $this->_applications;
		$result[1] = $total;
		$result[2] = $resumeconfig;
		
		return $result;
	}
	
	function &getUserType($u_id)
	{
		$db = &$this->getDBO();
		if (is_numeric($u_id) == false) return false;
		$query = "SELECT userrole.*, role.rolefor 
			FROM ".$db->nameQuote('#__wrecruit_userroles')." AS userrole
			JOIN ".$db->nameQuote('#__wrecruit_roles')." AS role ON userrole.role = role.id
			WHERE  uid  = ".$u_id;
		//echo '<br> sql '.$query;
		$db->setQuery($query);
		$result[0] = $db->loadObject();
		
		$usertype = array(
			'0' => array('value' => 1,'text' => JText::_('JS_EMPLOYER')),
			'1' => array('value' => 2,'text' => JText::_('JS_JOB_SEEKER')),);
		
		if (isset($result[0]))
			$lists['usertype'] = JHTML::_('select.genericList', $usertype, 'usertype', 'class="inputbox" '. '', 'value', 'text', $result[0]->rolefor);
		else
			$lists['usertype'] = JHTML::_('select.genericList', $usertype, 'usertype', 'class="inputbox" '. '', 'value', 'text', 1);
		$result[1] = $lists;
		
		return $result;
	}

	function &getResumebyId($id, $u_id)
	{
		$db = &$this->getDBO();
		if (is_numeric($u_id) == false) return false;
		if (($id != '') && ($id != 0)){
			if (is_numeric($id) == false) return false;
			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE id = ". $id ." AND uid  = ".$u_id;
			//echo '<br> sql '.$query;
			$db->setQuery($query);
			$this->_application = $db->loadObject();
			$result[0] = $this->_application;
		}
		//$result[2] = $this->getUserFields(3, this->_application->id); // company fields, id  USER FIELD NOT FOR RESUME
		$result[3] = $this->getFieldsOrdering(3); // resume fields
		if ($id){ // not new
			$result[4] = 1;
                        $result[5] = null;
                }else{ // new
                    $returnresult = $this->canAddNewResume($u_id);
                    $result[4] = $returnresult[0];
                    $result[5] = $returnresult[1];
                }

		return $result;
	}
	function getYesNo( $title ){
			$db =& JFactory::getDBO();
			$yesno = array();
			if($title)
				$yesno[] =  array('value' => '','text' => $title);

			$yesno[] =  array('value' => 1,	'text' => 'Yes');
			$yesno[] =  array('value' => 0,	'text' => 'No');
			
		return $yesno;	
	}
	function &getDepartmentbyId($departmentid)
	{
		$db = &$this->getDBO();
		if (is_numeric($departmentid) == false) return false;
		$query = "SELECT department.*,company.name as companyname 
					
		FROM ".$db->nameQuote('#__wrecruit_departments')." AS department
		JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON company.id = department.companyid
		WHERE  department.id = " . $departmentid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$department = $db->loadObject();

		
		return $department;
	}

	
	function &getDepartmentByIdForForm($departmentid, $uid){
		$db = &$this->getDBO();

		if (is_numeric($uid) == false) return false;
			if (($departmentid != '') && ($departmentid != 0)){
			if (is_numeric($departmentid) == false) return false;
			$query = "SELECT department.*
			FROM ".$db->nameQuote('#__wrecruit_departments')." AS department 
			WHERE department.id = ".$departmentid;
			//echo $query;
			$db->setQuery($query);
			$department = $db->loadObject();
			
		}
                $companies=$this->getCompanies($uid);

                if ( isset($department) ){
                        $lists['companies'] = JHTML::_('select.genericList', $companies , 'companyid', 'class="inputbox required" '. '', 'value', 'text', $department->companyid);

                }else{
                        $lists['companies'] = JHTML::_('select.genericList', $companies , 'companyid', 'class="inputbox required" '. '', 'value', 'text', '');
                }
		if(isset($department))$result[0] = $department;
		$result[1] = $lists;
		
		return $result;
	}
	
	function storeShortListCandidate($uid)
	{
		global $resumedata;
		$data = JRequest :: get('post');
		if (is_numeric($data['resumeid']) == false) return false;
		if (is_numeric($data['jobid']) == false) return false;
		if (is_numeric($uid) == false) return false;
                if ($this->shortListCandidateValidation($uid,$data['jobid'],$data['resumeid']) == false) return 3;
                $row = &$this->getTable('shortlistcandidate');
                $row->uid = $uid;
                $row->jobid = $data['jobid'];
                $row->cvid = $data['resumeid'];
                $row->status = 0;
                $row->created = date('Y-m-d H:i:s');
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	} 
	function shortListCandidateValidation($uid, $jobid, $resumeid)
	{
		$db =& JFactory::getDBO();
		$query = "SELECT COUNT(id) FROM #__wrecruit_shortlistcandidates
		WHERE  jobid = ".$jobid." AND cvid = ".$resumeid;
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0) return true; else return false;
	}

	function storeMessage($uid)
	{
                $data = JRequest :: get('post');
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
                if (is_numeric($data['resumeid']) == false) return false;
		if (is_numeric($data['jobid']) == false) return false;
		if (is_numeric($uid) == false) return false;
                $returnvalue = $this->messageValidation($data['jobid'],$data['resumeid']);
                if ($returnvalue != 1) return $returnvalue;
                
                $config = $this->getConfigByFor('messages');

                $data['status'] = $config['message_auto_approve'];
                $conflict = $this->checkString($data['subject'].$data['message']);
                if ($conflict[0] == false){
                    $data['status'] = $config['conflict_message_auto_approve'];
                    $data['isconflict'] = 1;
                    $data['conflictvalue'] = $conflict[1];
                }
                $row = &$this->getTable('message');
		if (!$row->bind($data)){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
                $row->sendby = $uid;
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		$returnvalue = $this->sendMessageEmail($row->id);
                //$this->sendMailtoAdmin($row->id,$data['uid'],7);
                if ($row->status == 1){ if($returnvalue == 1)return true; else return 4;
                }elseif ($row->status == 0) return 2;
	}
	function messageValidation($jobid, $resumeid)
	{

		if ((is_numeric($jobid) == false) ||($jobid == 0) || ($jobid == '')) return false;
		if ((is_numeric($resumeid) == false) ||($resumeid == 0) || ($resumeid == '')) return false;
		$db =& JFactory::getDBO();

		$query = "SELECT resume.uid FROM #__wrecruit_resume AS resume WHERE resume.id = ".$resumeid;
		$db->setQuery( $query );
		$resume = $db->loadObject();
		if(isset($resume)){
                    if($resume->uid) $returnvalue = 1; else return 5;
                }else return 5;

                $query = "SELECT job.uid FROM #__wrecruit_jobs AS job WHERE job.id = ".$jobid;
		$db->setQuery( $query );
		$job = $db->loadObject();
		if(isset($job)){
                    if($job->uid) $returnvalue = 1; else return 6;
                }else return 6;

                return $returnvalue;
	}
	function checkString($message)
	{
		//$message = 'This info@al-barr.com is testing message';
		//echo $message;
		$email_pattern = '/[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)*\@[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)+/';
		$domain_pattern = '@^(?:http://)?([^/]+)@i';
		$regex = '/(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?/';
                $retrun = array();
		preg_match($email_pattern, $message, $email);
		if($email[0] !=''){
			//echo '<br> Email '.$email[0];
                        $return[0] = false;
                        $return[1] = $email[0];
			return $return;
		}

		preg_match($domain_pattern,$message, $matches);
		$host = $matches[1];
		//if ($host != ''){
			//echo '<br> host '.$host;
			// get last two segments of host name
			preg_match('/[^.]+\.[^.]+$/', $host, $matches);
			if ($matches[0] != ''){
				//echo "<br>domain name is: {$matches[0]}\n";
                        $return[0] = false;
                        $return[1] = $matches[0];
			return $return;
			}
		//}

		preg_match($regex, $message, $phone);
		if ($phone[0] != ''){
                        $return[0] = false;
                        $return[1] = $phone[0];
			return $return;
		}
                $return[0] = true;
                return $return;
	}
	function &getCompanyInfoById($companyid) // this may not use
	{
		if (is_numeric($companyid) == false) return false;
	
		$db = &$this->getDBO();
		$query="SELECT company.name
		FROM ".$db->nameQuote('#__wrecruit_companies')." AS company
		WHERE company.id = " . $companyid;
		$db->setQuery($query);
		$company = $db->loadObject();
		//echo '<br> SQL '.$query;
		$query = "SELECT count(featuredjobs.id)
				
		FROM ".$db->nameQuote('#__wrecruit_featuredjobs')." AS featuredjobs
		JOIN ".$db->nameQuote('#__wrecruit_jobs')."  AS job ON featuredjobs.jobid = job.id
		JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
		WHERE  job.companyid = " . $companyid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$jobs = $db->loadResult();
		
		$query = "SELECT featuredjobs.*,job.created as jobcreated , job.title,company.name as companyname, country.name AS countryname, city.name AS cityname
				
		FROM ".$db->nameQuote('#__wrecruit_featuredjobs')." AS featuredjobs
		JOIN ".$db->nameQuote('#__wrecruit_jobs')."  AS job ON featuredjobs.jobid = job.id
		JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
		WHERE  job.companyid = " . $companyid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$info = $db->loadObjectList();
		$result[0]=$info;
		$result[1]=$jobs;
		$result[2]=$company;
		return $result;
		
		
	}
	
	function &getJobDetails($jobid) // this may not use
	{
		if (is_numeric($jobid) == false) return false;

                $db = &$this->getDBO();

		$query = "SELECT job.*, cat.cat_title , company.name as companyname, jobtype.title AS jobtypetitle
				,  shift.title as shifttitle
				, salaryfrom.rangestart AS salaryfrom, salaryto.rangestart AS salaryto, salarytype.title AS salarytype
				,mineducation.title AS mineducationtitle
				, minexperience.title AS minexperiencetitle,agefrom.title AS agefrom,ageto.title AS ageto
				, country.name AS countryname, city.name AS cityname,careerlevel.title AS careerleveltitle
		FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
		JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
		JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
		JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryfrom ON job.salaryrangefrom = salaryfrom.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryto ON job.salaryrangeto = salaryto.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrangetypes')." AS salarytype ON job.salaryrangetype = salarytype.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS mineducation ON job.mineducationrange = mineducation.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_experiences')." AS minexperience ON job.minexperiencerange = minexperience.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_shifts')." AS shift ON job.shift = shift.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_ages')." AS ageto ON job.ageto = ageto.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_ages')." AS agefrom ON job.agefrom = agefrom.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_careerlevels')." AS careerlevel ON job.careerlevel = careerlevel.id
		WHERE  job.id = " . $jobid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$details = $db->loadObject();
		
		return $details;
	}
	
	function &getAllForDetails($limit,$limitstart) // may not use this function
	{
		$db = &$this->getDBO();
		$result = array();

		/*$query =  "SELECT COUNT(featuredjob.id)
				FROM ".$db->nameQuote('#__wrecruit_featuredjobs')." AS featuredjob 
				JOIN ".$db->nameQuote('#__wrecruit_jobs')." AS  job ON job.id=featuredjob.jobid
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS comapny ON comapny.id=job.companyid ";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;*/

		$query = "SELECT featuredjob.*,job.title,comapny.name,comapny.city
				FROM ".$db->nameQuote('#__wrecruit_featuredjobs')." AS featuredjob 
				JOIN ".$db->nameQuote('#__wrecruit_jobs')." AS  job ON job.id=featuredjob.jobid
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS comapny ON comapny.id=job.companyid 
				GROUP BY featuredjob.jobid";
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$jobs = $db->loadObjectList();
		
		
		
		$query = "SELECT goldjob.*,job.title,comapny.name,comapny.city
				FROM ".$db->nameQuote('#__wrecruit_goldjobs')." AS goldjob 
				JOIN ".$db->nameQuote('#__wrecruit_jobs')." AS  job ON job.id=goldjob.jobid
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS comapny ON comapny.id=job.companyid 
				GROUP BY goldjob.jobid";
				
		$db->setQuery($query, $limitstart, $limit);
		$goldjobs = $db->loadObjectList();
		$query = "SELECT featuredcompany.*,comapny.name,comapny.city
				FROM ".$db->nameQuote('#__wrecruit_featuredcompanies')." AS featuredcompany 
				JOIN ".$db->nameQuote('#__wrecruit_companies')." AS comapny ON comapny.id=featuredcompany.companyid 
				GROUP BY featuredcompany.companyid";
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$featuredcompanies = $db->loadObjectList();
		
		
		
		$query = "SELECT goldcompany.*,comapny.name,comapny.city
				FROM ".$db->nameQuote('#__wrecruit_goldcompanies')." AS goldcompany 
				
				JOIN ".$db->nameQuote('#__wrecruit_companies')." AS comapny ON comapny.id=goldcompany.companyid 
				GROUP BY goldcompany.companyid";
				
		$db->setQuery($query, $limitstart, $limit);
		$goldcompanies = $db->loadObjectList();
		
		$result[0] = $jobs;
		$result[1] = $goldjobs;
		$result[2] = $featuredcompanies;
		$result[3] = $goldcompanies;
		
		
		return $result;
	}

// Payment System Start
	
	function storeGoldResume($uid,$resumeid)
	{
		global $resumedata;
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($resumeid) == false) ||($resumeid == 0) || ($resumeid == '')) return false;
		$db = &$this->getDBO();
		$query = "SELECT COUNT(id)
				FROM ".$db->nameQuote('#__wrecruit_resume')." 
				WHERE uid = ".$uid." AND id = ".$resumeid." AND status = 1";
		//echo '<br> SQL '.$query;
		$db->setQuery( $query );
		$resumes = $db->loadResult();
		if($resumes <= 0) return 3;// company not exsit or not approved
		
		if($this->canAddNewGoldResume($uid) == false) return 5; // can not add new gold resume
		
                $query = "SELECT package.id, package.goldresume
                            , (SELECT COUNT(id) FROM #__wrecruit_goldresumes WHERE packageid = package.id  AND uid = ".$uid.") AS resumeavail
                            FROM #__wrecruit_jobseekerpaymenthistory AS payment
                            JOIN #__wrecruit_jobseekerpackages AS package ON package.id = payment.packageid
                            WHERE payment.uid = ".$uid."
                            AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                            AND payment.transactionverified = 1 AND payment.status = 1";
                //echo $query;
                $db->setQuery($query);
                $packages = $db->loadObjectList();
                foreach($packages AS $package){
			if($unlimited == 0){
                            if ($package->goldresume != -1){
                                if($package->goldresume > $package->resumeavail){
                                    $packageid = $package->id;
                                }
                            }else{
                                $packageid = $package->id;
                                 $unlimited = 1;
                            }
                        }
                }
		$row = &$this->getTable('goldresume');
		$data = JRequest :: get('post');
		$config = $this->getConfigByFor('goldresume');
                $row->uid = $uid;
                $row->resumeid = $resumeid;
                $row->status = $config['goldresume_autoapprove'];
                $row->packageid =$packageid ;
                $row->created = date('Y-m-d H:i:s');

		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->GoldResumeValidation($uid, $resumeid);
			if ($result == false) return 6;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	} 
	
	function GoldResumeValidation($uid, $resumeid)
	{
		
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($resumeid) == false) ||($resumeid == 0) || ($resumeid == '')) return false;
		$db =& JFactory::getDBO();
		
		$query = "SELECT COUNT(goldresume.id)  
		FROM #__wrecruit_goldresumes  AS goldresume
		JOIN #__wrecruit_jobseekerpackages AS package ON package.id=goldresume.packageid
		WHERE goldresume.uid = ".$uid ." AND goldresume.resumeid = ".$resumeid." 
		AND DATE_ADD(goldresume.created,INTERVAL package.goldresumeexpireindays DAY) >= CURDATE()";
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0) return true; else return false;
	}
	
	function canAddNewGoldResume($uid)
	{
		$db = &$this->getDBO();
		
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;

		$query = "SELECT package.goldresume, package.packageexpireindays, payment.created
		FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid." 
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
		AND payment.transactionverified = 1 AND payment.status = 1";
		$db->setQuery($query);
		$resumes = $db->loadObjectList();
		$unlimited = 0;
		foreach($resumes AS $resume){
			if($unlimited == 0){
				if ($resume->goldresume != -1){
					$goldresume = $goldresume + $resume->goldresume;
				}else $unlimited = 1;
			}	
		}
		if ($unlimited == 0){
        		if ($goldresume == 0) return 0; //can not add new job
			$query = "SELECT COUNT(resume.id) 
			FROM ".$db->nameQuote('#__wrecruit_goldresumes')." AS resume
			WHERE resume.uid = ".$uid;
			$db->setQuery($query);
			$totalresumes = $db->loadResult();
			
			if ($goldresume <= $totalresumes) return 0; //can not add new job
			else return 1;
			
		}elseif ($unlimited == 1) return 1; // unlimited
		
		return 0;
	}

	function storeFeaturedResume($uid,$resumeid)
	{
		global $resumedata;
		if ((is_numeric($resumeid) == false) ||($resumeid == 0) || ($resumeid == '')) return false;
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		$db = &$this->getDBO();
		$query = "SELECT COUNT(id)
				FROM ".$db->nameQuote('#__wrecruit_resume')." 
				WHERE uid = ".$uid." AND id = ".$resumeid." AND status = 1";
		$db->setQuery( $query );
		$resumes = $db->loadResult();
		if($resumes <= 0) return 3;// company not exsit or not approved
		
		if($this->canAddNewFeaturedResume($uid) == false) return 5; // can not add new gold comapuny

                $query = "SELECT package.id, package.featuredresume
                            , (SELECT COUNT(id) FROM #__wrecruit_featuredresumes WHERE packageid = package.id  AND uid = ".$uid.") AS resumeavail
                            FROM #__wrecruit_jobseekerpaymenthistory AS payment
                            JOIN #__wrecruit_jobseekerpackages AS package ON package.id = payment.packageid
                            WHERE payment.uid = ".$uid."
                            AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                            AND payment.transactionverified = 1 AND payment.status = 1";
                $db->setQuery($query);
                $packages = $db->loadObjectList();
                foreach($packages AS $package){
			if($unlimited == 0){
                            if ($package->featuredresume != -1){
                                if($package->featuredresume > $package->resumeavail){
                                    $packageid = $package->id;
                                }
                            }else{
                                $packageid = $package->id;
                                 $unlimited = 1;
                            }
                        }
                }
		$row = &$this->getTable('featuredresume');
		$data = JRequest :: get('post');
		$config = $this->getConfigByFor('featuredresume');

                $row->uid = $uid;
                $row->resumeid = $resumeid;
                $row->status = $config['featuredresume_autoapprove'];
                $row->packageid =$packageid ;
                $row->created = date('Y-m-d H:i:s');
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->featuredResumeValidation($uid, $resumeid);
			if ($result == false) return 6;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	} 
	
	
	function featuredResumeValidation($uid, $resumeid)
	{
		
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($resumeid) == false) ||($resumeid == 0) || ($resumeid == '')) return false;

                $db =& JFactory::getDBO();
		
		$query = "SELECT COUNT(featuredresume.id)  
		FROM #__wrecruit_featuredresumes  AS featuredresume
		JOIN #__wrecruit_jobseekerpackages AS package ON package.id=featuredresume.packageid
		WHERE featuredresume.uid = ".$uid ." AND featuredresume.resumeid = ".$resumeid." 
		AND DATE_ADD(featuredresume.created,INTERVAL package.freaturedresumeexpireindays DAY) >= CURDATE()";
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0) return true; else return false;
	}
	
	function canAddNewFeaturedResume($uid) 
	{
		$db = &$this->getDBO();
		
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;

		$query = "SELECT package.id, package.featuredresume, package.packageexpireindays, payment.created
		FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid." 
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
		AND payment.transactionverified = 1 AND payment.status = 1";
		$db->setQuery($query);
		$resumes = $db->loadObjectList();
		$unlimited = 0;
		foreach($resumes AS $resume){
			if($unlimited == 0){
				if ($resume->featuredresume != -1){
					$featuredresume = $featuredresume + $resume->featuredresume;
				}else $unlimited = 1;
			}	
		}
		
		if ($unlimited == 0){
		if ($featuredresume == 0) return 0; //can not add new job
		
			$query = "SELECT COUNT(resume.id) 
			FROM ".$db->nameQuote('#__wrecruit_featuredresumes')." AS resume
			WHERE resume.uid = ".$uid;
			$db->setQuery($query);
			$totalresumes = $db->loadResult();
			
			if ($featuredresume <= $totalresumes) return 0; //can not add new job
			else return 1;
			
		}elseif ($unlimited == 1) return 1; // unlimited
		return 0;
	}
	
	function storeFeaturedCompany($uid,$companyid)
	{
		global $resumedata;
		if ((is_numeric($companyid) == false) ||($companyid == 0) || ($companyid == '')) return false;
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;

                $db = &$this->getDBO();
		$query = "SELECT COUNT(id)
				FROM ".$db->nameQuote('#__wrecruit_companies')." 
				WHERE uid = ".$uid." AND id = ".$companyid." AND status = 1";
		$db->setQuery( $query );
		$jobs = $db->loadResult();
		if($jobs <= 0) return 3;// company not exsit or not approved
		
		if($this->canAddNewFeaturedCompany($uid) == false) return 5; // can not add new gold comapuny

                $query = "SELECT package.id, package.featuredcompaines
                            , (SELECT COUNT(id) FROM #__wrecruit_featuredcompanies WHERE packageid = package.id  AND uid = ".$uid.") AS companyavail
                            FROM #__wrecruit_employerpaymenthistory AS payment
                            JOIN #__wrecruit_employerpackages AS package ON package.id = payment.packageid
                            WHERE payment.uid = ".$uid."
                            AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                            AND payment.transactionverified = 1 AND payment.status = 1";
              $db->setQuery($query);
                $packages = $db->loadObjectList();
                foreach($packages AS $package){
			if($unlimited == 0){
                            if ($package->featuredcompaines != -1){
                                if($package->featuredcompaines > $package->companyavail){
                                    $packageid = $package->id;
                                }
                            }else{
                                $packageid = $package->id;
                                 $unlimited = 1;
                            }
                        }
                }
		$row = &$this->getTable('featuredcompany');
		$data = JRequest :: get('post');
		$config = $this->getConfigByFor('featuredcompany');

                $row->uid = $uid;
                $row->companyid = $companyid;
                $row->status = $config['featuredcompany_autoapprove'];
                $row->packageid = $packageid;
                $row->created = date('Y-m-d H:i:s');
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->featuredCompanyValidation($uid, $companyid);
			if ($result == false) return 6;
		}
		
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	} 
	
	function featuredCompanyValidation($uid, $companyid)
	{
		
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($companyid) == false) ||($companyid == 0) || ($companyid == '')) return false;

                $db =& JFactory::getDBO();
		
		$query = "SELECT COUNT(featuredcompany.id)  
		FROM #__wrecruit_featuredcompanies  AS featuredcompany
		JOIN #__wrecruit_employerpackages AS package ON package.id=featuredcompany.packageid
		WHERE featuredcompany.uid = ".$uid ." AND featuredcompany.companyid = ".$companyid." 
		AND DATE_ADD(featuredcompany.created,INTERVAL package.featuredcompaniesexpireindays DAY) >= CURDATE()";
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0) return true; else return false;
	}
	
	function storeGoldCompany($uid, $companyid)
	{
		global $resumedata;
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($companyid) == false) ||($companyid == 0) || ($companyid == '')) return false;
		$db = &$this->getDBO();
		$query = "SELECT COUNT(id)
				FROM ".$db->nameQuote('#__wrecruit_companies')." 
				WHERE uid = ".$uid." AND id = ".$companyid." AND status = 1";
		$db->setQuery( $query );
		$jobs = $db->loadResult();
		if($jobs <= 0) return 3;// company not exsit or not approved
		
		if($this->canAddNewGoldCompany($uid) == false) return 5; // can not add new gold comapuny
		
                $query = "SELECT package.id, package.goldcompanies
                            , (SELECT COUNT(id) FROM #__wrecruit_goldcompanies WHERE packageid = package.id  AND uid = ".$uid.") AS companyavail
                            FROM #__wrecruit_employerpaymenthistory AS payment
                            JOIN #__wrecruit_employerpackages AS package ON package.id = payment.packageid
                            WHERE payment.uid = ".$uid."
                            AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                            AND payment.transactionverified = 1 AND payment.status = 1";
                $db->setQuery($query);
                $packages = $db->loadObjectList();
                foreach($packages AS $package){
			if($unlimited == 0){
                            if ($package->goldcompanies != -1){
                                if($package->goldcompanies > $package->companyavail){
                                    $packageid = $package->id;
                                }
                            }else{
                                $packageid = $package->id;
                                 $unlimited = 1;
                            }
                        }
                }
		$row = &$this->getTable('goldcompany');
		$data = JRequest :: get('post');
		$config = $this->getConfigByFor('goldcompany');

                $row->uid = $uid;
                $row->companyid = $companyid;
                $row->status = $config['goldcompany_autoapprove'];
                $row->packageid =$packageid;
                $row->created = date('Y-m-d H:i:s');
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->goldCompanyValidation($uid, $companyid);
			echo $uid.$companyid;
			if ($result == false) return 6;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	} 
	
	
	function goldCompanyValidation($uid, $companyid)
	{
		
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($companyid) == false) ||($companyid == 0) || ($companyid == '')) return false;

                $db =& JFactory::getDBO();
		
		$query = "SELECT COUNT(gold.id)  
		FROM #__wrecruit_goldcompanies  AS gold
		JOIN #__wrecruit_employerpackages AS package ON package.id=gold.packageid
		WHERE gold.uid = ".$uid ." AND gold.companyid = ".$companyid." 
		AND DATE_ADD(gold.created,INTERVAL package.goldcompaniesexpireindays DAY) >= CURDATE()";
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0) return true; else return false;
	}
	function storeFeaturedJobs($uid, $jobid)
	{
		global $resumedata;
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($jobid) == false) ||($jobid == 0) || ($jobid == '')) return false;
		$db = &$this->getDBO();
		$query = "SELECT COUNT(id)
				FROM ".$db->nameQuote('#__wrecruit_jobs')." 
				WHERE uid = ".$uid." AND id = ".$jobid." AND status = 1";
		//echo '<br> SQL '.$query;
		$db->setQuery( $query );
		$jobs = $db->loadResult();
		if($jobs <= 0) return 3;// job not exsit or not approved
		
		if($this->canAddNewFeaturedJob($uid) == false) return 5;
		
                $query = "SELECT package.id, package.featuredjobs
                            , (SELECT COUNT(id) FROM #__wrecruit_featuredjobs WHERE packageid = package.id  AND uid = ".$uid.") AS jobavail
                            FROM #__wrecruit_employerpaymenthistory AS payment
                            JOIN #__wrecruit_employerpackages AS package ON package.id = payment.packageid
                            WHERE payment.uid = ".$uid."
                            AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                            AND payment.transactionverified = 1 AND payment.status = 1";
               // echo $query;
                $db->setQuery($query);
                $packages = $db->loadObjectList();
                foreach($packages AS $package){
			if($unlimited == 0){
                            if ($package->featuredjobs != -1){
                                if($package->featuredjobs > $package->jobavail){
                                    $packageid = $package->id;
                                }
                            }else{
                                $packageid = $package->id;
                                 $unlimited = 1;
                            }
                        }
                }
/*
                $query = "SELECT package.id,  payment.created
		FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid." 
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE() 
		AND payment.transactionverified = 1";
		//echo $query;
		$db->setQuery($query);
		$packages = $db->loadObjectList();
		$unlimited = 0;
		foreach($packages AS $package){
			if($unlimited == 0){
				if ($package->featuredjobs != -1){
					$packageid = $package->id;
				}else{
					$packageid = $package->id;
					 $unlimited = 1;
				}
			}	
		}
*/
		$row = &$this->getTable('featuredjob');
		$data = JRequest :: get('post');
		$config = $this->getConfigByFor('featuredjob');
			
			$row->uid = $uid;
			$row->jobid = $jobid;
			$row->status = $config['featuredjob_autoapprove'];
  			 $row->created = date('Y-m-d H:i:s');
			 $row->packageid=$packageid;
   			//$row->startdate = ;
			//$row->enddate = ;
			//$row->created = date('Y-m-d H:i:s');
	

		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->featuredJobValidation($uid, $jobid);
			if ($result == false)
			{
				return 6;
			}
		}
		
		
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	} 
	
	function featuredJobValidation($uid, $jobid)
	{
		
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($jobid) == false) ||($jobid == 0) || ($jobid == '')) return false;

                $db =& JFactory::getDBO();
		
		$query = "SELECT COUNT(featuredjob.id)  
		FROM #__wrecruit_featuredjobs  AS featuredjob
		JOIN #__wrecruit_employerpackages AS package ON package.id=featuredjob.packageid
		WHERE featuredjob.uid = ".$uid ." AND featuredjob.jobid = ".$jobid." 
		AND DATE_ADD(featuredjob.created,INTERVAL package.featuredjobsexpireindays DAY) >= CURDATE()";
	
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		//echo '<br>r'.$result;
		if ($result == 0)
			return true;
		else
			return false;
			
	}
	
	
	function storeGoldJobs($uid, $jobid)
	{
		
		global $resumedata;
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($jobid) == false) ||($jobid == 0) || ($jobid == '')) return false;
		$db = &$this->getDBO();
		$query = "SELECT COUNT(id)
				FROM ".$db->nameQuote('#__wrecruit_jobs')." 
				WHERE uid = ".$uid." AND id = ".$jobid." AND status = 1";

		$db->setQuery( $query );
		$jobs = $db->loadResult();
		if($jobs <= 0) return 3;// job not exsit or not approved
		
		
		
		if($this->canAddNewGoldJob($uid) == false) return 5; // can not add new gold job
		
                $query = "SELECT package.id, package.goldjobs
                            , (SELECT COUNT(id) FROM #__wrecruit_goldjobs WHERE packageid = package.id  AND uid = ".$uid.") AS jobavail
                            FROM #__wrecruit_employerpaymenthistory AS payment
                            JOIN #__wrecruit_employerpackages AS package ON package.id = payment.packageid
                            WHERE payment.uid = ".$uid."
                            AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                            AND payment.transactionverified = 1 AND payment.status = 1";
                //echo $query;
                $db->setQuery($query);
                $packages = $db->loadObjectList();
                foreach($packages AS $package){
			if($unlimited == 0){
                            if ($package->goldjobs != -1){
                                if($package->goldjobs > $package->jobavail){
                                    $packageid = $package->id;
                                }
                            }else{
                                $packageid = $package->id;
                                 $unlimited = 1;
                            }
                        }
                }
                /*
		$query = "SELECT package.id,  payment.created
		FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid." 
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE() 
		AND payment.transactionverified = 1";
		//echo $query;
		$db->setQuery($query);
		$packages = $db->loadObjectList();
		$unlimited = 0;
		foreach($packages AS $package){
			if($unlimited == 0){
				if ($package->goldjobs != -1){
					$packageid = $package->id;
				}else{
					$packageid = $package->id;
					 $unlimited = 1;
				}
			}	
		}
		*/
		$row = &$this->getTable('goldjob');
		$data = JRequest :: get('post');
		$config = $this->getConfigByFor('goldjob');
			
			$row->uid = $uid;
			$row->jobid = $jobid;
			$row->status = $config['goldjob_autoapprove'];
  			 $row->created = date('Y-m-d H:i:s');
			 $row->packageid=$packageid;
   			//$row->startdate = ;
			//$row->enddate = ;
			//$row->created = date('Y-m-d H:i:s');
	

		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		
		if ($data['id'] == ''){ // only for new
			$result=$this->goldJobValidation($uid, $jobid);
			if ($result == false)
			{
				return 6;
			}
		}
		
		
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	} 
	
	function goldJobValidation($uid, $jobid)
	{
		
		if ((is_numeric($uid) == false) ||($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($jobid) == false) ||($jobid == 0) || ($jobid == '')) return false;

                $db =& JFactory::getDBO();
		
		$query = "SELECT COUNT(goldjob.id)  
		FROM #__wrecruit_goldjobs  AS goldjob
		JOIN #__wrecruit_employerpackages AS package ON package.id=goldjob.packageid
		WHERE goldjob.uid = ".$uid ." AND goldjob.jobid = ".$jobid." 
		AND DATE_ADD(goldjob.created,INTERVAL package.goldjobsexpireindays DAY) >= CURDATE()";
	
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		//echo '<br>r'.$result;
		if ($result == 0)
			return true;
		else
			return false;
			
	}
	
	
	function &getJobSeekerPackages($limit,$limitstart)
	{
		$db = &$this->getDBO();
		$result = array();

		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages').' WHERE status = 1';
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT package.* FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package WHERE status = 1";
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$packages = $db->loadObjectList();

		$result[0] = $packages;
		$result[1] = $total;
		
		return $result;
	}

	
	function &getJobSeekerPackageById($packageid)
	{
		if (is_numeric($packageid) == false) return false;
	
		$db = &$this->getDBO();
		


		$query = "SELECT package.* FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package WHERE id = ".$packageid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$package = $db->loadObject();
		
		return $package;
	}
	
	function storeJobSeekerPackageHistory($referenceid,$autoassign,$data)
	{
		global $resumedata;
		$row = &$this->getTable('jobseekerpaymenthistory');

                if ($autoassign == 0) $data = JRequest :: get('post'); // get data from form
		
		if (is_numeric($data['packageid']) == false) return false;
		if (is_numeric($data['uid']) == false) return false;
		$db = &$this->getDBO();
		$result = array();


		$query = "SELECT package.* FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package WHERE id = ".$data['packageid'];
		//echo $query.'<br/>';
		$db->setQuery($query);
		$package = $db->loadObject();
		if(isset($package)){
			$packageconfig = $this->getConfigByFor('package');
                        $row->uid = $data['uid'];
			$row->packageid = $package->id;
			$row->packagetitle = $package->title;
			$row->packageprice = $package->price;
                        $paidamount = $package->price;
                        $discountamount = 0;

                        if ($package->price != 0){
                           $curdate = date('Y-m-d H:i:s');
                            if (($package->discountstartdate <= $curdate) && ($package->discountenddate >= $curdate)){
                                 if($package->discounttype == 1){ //%
                                     $discountamount = ($package->price * $package->discount)/100;
                                      $paidamount = $package->price - $discountamount;
                                 }else{ // amount
                                     $discountamount = $package->discount;
                                     $paidamount = $package->price - $package->discount;
                                 }
                            }
                            $row->transactionverified = 0;
                            $row->transactionautoverified = 0;
                            $row->status = 1;
                        }else{
                            if($packageconfig['onlyonce_jobseeker_getfreepackage'] == '1'){ // can't get free package more then once
                                $query = "SELECT COUNT(package.id) FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package
                                    JOIN ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS payment ON payment.packageid = package.id
                                    WHERE package.price = 0 AND payment.uid = ".$data['uid'];
                                //echo $query.'<br/>';
                                $db->setQuery($query);
                                $freepackage = $db->loadResult();
                                if($freepackage > 0) return 5;// can't get free package more then once
                            }
                            $row->transactionverified = 1;
                            $row->transactionautoverified = 1;
                            $row->status = $packageconfig['jobseeker_freepackage_autoapprove'];
                        }
			$row->discountamount = $discountamount;
			$row->paidamount = $paidamount;

                        $row->discountmessage = $package->discountmessage;
			$row->packagestartdate = $package->discountstartdate;
			$row->packageenddate = $package->discountenddate;
			$row->resumeallow = $package->resumeallow;
			$row->coverlettersallow = $package->coverlettersallow;
			$row->applyjobs = $package->applyjobs;
			$row->jobsearch = $package->jobsearch;
			$row->savejobsearch = $package->savejobsearch;
			$row->featuredresume = $package->featuredresume;
			$row->goldresume = $package->goldresume;
			$row->video = $package->video;
			$row->packageexpireindays = $package->packageexpireindays;
			$row->packageshortdetails = $package->shortdetails;
			$row->packagedescription = $package->description;
			$row->created = date('Y-m-d H:i:s');
                        $row->referenceid = $referenceid;
		}else{ 
                    return false;
                }

		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
                 $this->sendMailtoAdmin($row->id,$data['uid'],7);
		return true;
	} 
	
	function &getEmployerPackages($limit,$limitstart)
	{
		$db = &$this->getDBO();
		$result = array();

		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_employerpackages').' WHERE status = 1';
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT package.* FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package WHERE status = 1";
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$packages = $db->loadObjectList();

		$result[0] = $packages;
		$result[1] = $total;
		
		return $result;
	}

	function &getEmployerPackageById($packageid,$uid)
	{
		if (is_numeric($packageid) == false) return false;
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$db = &$this->getDBO();
		$result = array();


		$query = "SELECT package.* FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package WHERE id = ".$packageid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$package = $db->loadObject();
		$lists = '';
		$payment_multicompanies = '' ;

		
		if(! isset($this->_config)){
			$this->getConfig('payment');
		}	
		
		foreach ($this->_config as $conf){
			if ($conf->configname == 'payment_multicompanies')
					$payment_multicompanies = $conf->configvalue;
		}
		//echo '<br> SQL '.$payment_multicompanies;
		if($payment_multicompanies == '0')
		{
			$companies = $this->getCompanies($uid);
			$lists['companies'] = JHTML::_('select.genericList', $companies , 'companyid', 'class="inputbox required" '. '', 'value', 'text', '');	
		}
		$result[0] = $package;
		$result[1] = $payment_multicompanies;
		$result[2] = $lists;
		
		
		return $result;
	}
	
	function &getEmployerPackageInfoById($packageid)
	{
		if (is_numeric($packageid) == false) return false;
		$db = &$this->getDBO();


		$query = "SELECT package.* FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package WHERE id = ".$packageid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$package = $db->loadObject();

		return $package;
	}
	
	function &getJobSeekerPackageInfoById($packageid)
	{
		if (is_numeric($packageid) == false) return false;
		$db = &$this->getDBO();


		$query = "SELECT package.* FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package WHERE id = ".$packageid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$package = $db->loadObject();

		return $package;
	}
	
	
	function storeEmployerPackageHistory($referenceid,$autoassign,$data)
	{
		$row = &$this->getTable('employerpaymenthistory');

                if ($autoassign == 0) $data = JRequest :: get('post'); // get data from form

                if (is_numeric($data['packageid']) == false) return false;
		if (is_numeric($data['uid']) == false) return false;
		$db = &$this->getDBO();
		$result = array();


		$query = "SELECT package.* FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package WHERE id = ".$data['packageid'];
		//echo $query.'<br/>';
		$db->setQuery($query);
		$package = $db->loadObject();
		if(isset($package)){
			$packageconfig = $this->getConfigByFor('package');
			$row->uid = $data['uid'];
			$row->companyid = $data['companyid'];
			$row->packageid = $data['packageid'];
			
			$row->packagetitle = $package->title;
			$row->packageprice = $package->price;
                        $paidamount = $package->price;
                        $discountamount = 0;

                        if ($package->price != 0){
                           $curdate = date('Y-m-d H:i:s');
                            if (($package->discountstartdate <= $curdate) && ($package->discountenddate >= $curdate)){
                                 if($package->discounttype == 1){ //%
                                     $discountamount = ($package->price * $package->discount)/100;
                                      $paidamount = $package->price - $discountamount;
                                 }else{ // amount
                                     $discountamount = $package->discount;
                                     $paidamount = $package->price - $package->discount;
                                 }
                            }
                            $row->transactionverified = 0;
                            $row->transactionautoverified = 0;
                            $row->status = 1;
                        }else{ //free
                            if($packageconfig['onlyonce_employer_getfreepackage'] == '1'){ // can't get free package more then once
                                $query = "SELECT COUNT(package.id) FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
                                    JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
                                    WHERE package.price = 0 AND payment.uid = ".$data['uid'];
                                //echo $query.'<br/>';
                                $db->setQuery($query);
                                $freepackage = $db->loadResult();
                                if($freepackage > 0) return 5;// can't get free package more then once
                            }
                            $row->transactionverified = 1;
                            $row->transactionautoverified = 1;
                            $row->status = $packageconfig['employer_freepackage_autoapprove'];
                        }
			$row->discountamount = $discountamount;
			$row->paidamount = $paidamount;
			$row->discountmessage = $package->discountmessage;
			$row->packagediscountstartdate = $package->discountstartdate;
			$row->packagediscountenddate = $package->discountenddate;
			$row->companiesallow = $package->companiesallow;
			$row->jobsallow = $package->jobsallow;
			$row->viewresumeindetails = $package->viewresumeindetails;
			$row->resumesearch = $package->resumesearch;
			$row->saveresumesearch = $package->saveresumesearch;
			$row->featuredcompanies = $package->featuredcompaines;
			$row->goldcompanies = $package->goldcompanies;
			$row->featuredjobs = $package->featuredjobs;
			$row->goldjobs = $package->goldjobs;
			//$row->candidateshortlist = $package->jobseekershortlist;
			$row->video = $package->video;
			$row->map = $package->map;
			$row->packageexpireindays = $package->packageexpireindays;
			$row->packageshortdetails = $package->shortdetails;
			$row->packagedescription = $package->description;
			$row->created = date('Y-m-d H:i:s');
                        $row->referenceid = $referenceid;
		}else{ 
                    return false;
                }

		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
                 $this->sendMailtoAdmin($row->id,$data['uid'],6);
		return true;
	} 

        function updateEmployerPackageHistory($firstname,$lastname, $email, $amount, $referenceid
                    , $tx_token, $date, $paypalstatus,$status)
	{
		$db = &$this->getDBO();

                $query = "UPDATE ".$db->nameQuote('#__wrecruit_employerpaymenthistory')."
                    SET payer_firstname = ".$db->quote($firstname)."
                    , payer_lastname = ".$db->quote($lastname)."
                    , payer_email = ".$db->quote($email)."
                    , payer_amount = ".$amount."    
                    , payer_tx_token = ".$db->quote($tx_token)."
                    , transactionverified = ".$status."
                    , transactionautoverified = 1
                    , verifieddate = ".$db->quote($date)."
                    , payer_status = ".$db->quote($paypalstatus)."
                    WHERE referenceid = ".$db->quote($referenceid);
                //echo '<br>sql '.$query;
                $db->setQuery( $query );
                $db->query();

		return true;
	}
        function updateJobSeekerPackageHistory($firstname,$lastname, $email, $amount, $referenceid
                    , $tx_token, $date, $paypalstatus,$status)
	{
		$db = &$this->getDBO();

                $query = "UPDATE ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')."
                    SET payer_firstname = ".$db->quote($firstname)."
                    , payer_lastname = ".$db->quote($lastname)."
                    , payer_email = ".$db->quote($email)."
                    , payer_amount = ".$amount."
                    , payer_tx_token = ".$db->quote($tx_token)."
                    , transactionverified = ".$status."
                    , transactionautoverified = 1
                    , verifieddate = ".$db->quote($date)."
                    , payer_status = ".$db->quote($paypalstatus)."
                    WHERE referenceid = ".$db->quote($referenceid);
                //echo '<br>sql '.$query;
                $db->setQuery( $query );
                $db->query();

		return true;
	}

        function &getEmployerPurchaseHistory($uid,$limit,$limitstart)
	{
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
                
		$db = &$this->getDBO();
		$result = array();

		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." WHERE uid = ".$uid." AND status = 1";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT purchase.paidamount, purchase.transactionverified,purchase.created
                            ,package.id, package.title,package.companiesallow, package.jobsallow, package.packageexpireindays
                            FROM ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS purchase
                            JOIN ".$db->nameQuote('#__wrecruit_employerpackages')." AS package ON package.id = purchase.packageid
                            WHERE uid = ".$uid." AND purchase.status = 1 ORDER BY purchase.created DESC";
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$packages = $db->loadObjectList();

		$result[0] = $packages;
		$result[1] = $total;
		
		return $result;
	}
	function &getJobSeekerPurchaseHistory($uid,$limit,$limitstart)
	{
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$db = &$this->getDBO();
		$result = array();

		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." WHERE uid = ".$uid." AND status = 1";;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT purchase.paidamount,purchase.transactionverified,purchase.created,
						package.id,package.title,package.resumeallow,package.coverlettersallow,package.packageexpireindays
						FROM ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS purchase 
						JOIN ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package ON package.id = purchase.packageid
       					WHERE uid = ".$uid." AND purchase.status = 1 ORDER BY purchase.created DESC ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query, $limitstart, $limit);
		$packages = $db->loadObjectList();

		$result[0] = $packages;
		$result[1] = $total;
		
		return $result;
	}

        //Payment system end
	
	function storeDepartment()
	{
		global $resumedata;
		$row = &$this->getTable('department');
		$data = JRequest :: get('post');


		if ($data['id'] == '') { // only for new 
                    $config = $this->getConfigByFor('department');
                    $data['status'] = $config['department_auto_approve'];
		}
		if (!$row->bind($data)){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErroMrsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		if ($data['id'] == '') $this->sendMailtoAdmin($row->id,$data['uid'],5); //only for new
                return true;
	}
	
	
	
	function &getCoverLetterbyId($id, $u_id)
	{
		$db = &$this->getDBO();
		if($u_id) if($u_id)if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		
		if (($id != '') && ($id != 0)){
			if (is_numeric($id) == false) return false;
			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_coverletters')." WHERE id = ". $id;
			//echo '<br> sql '.$query;
			$db->setQuery($query);
			$this->_application = $db->loadObject();
			$result[0] = $this->_application;
		}
		if ($id) // not new
			$result[4] = 1;
		else // new
			if (isset($u_id)) {
				if (is_numeric($u_id) == false) return false;
				$canaddreturnvalue = $this->canAddNewCoverLetter($u_id);
                                $result[4] = $canaddreturnvalue[0];
                                $result[5] = $canaddreturnvalue[1];
			}	
		return $result;
	}

	function &getMyCoverLettersbyUid($u_id,$limit,$limitstart)
	{
		$db = &$this->getDBO();
		if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		$result = array();
		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_coverletters')." WHERE uid  = ".$u_id;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		//$limit = $limit ? $limit : 5;
                if ( $total <= $limitstart ) $limitstart = 0;
		
		$query = "SELECT letter.* 
					FROM ".$db->nameQuote('#__wrecruit_coverletters')." AS letter
					WHERE letter.uid  = ".$u_id ;
		//echo '<br> sql '.$query;
		$db->setQuery($query);
		$db->setQuery($query, $limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		
		return $result;
	}
	
	function &getMyJobSearchesbyUid($u_id,$limit,$limitstart)
	{
		if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		$db = &$this->getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobsearches')." WHERE uid  = ".$u_id;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		//$limit = $limit ? $limit : 5;
                if ( $total <= $limitstart ) $limitstart = 0;
		
		$query = "SELECT search.* 
					FROM ".$db->nameQuote('#__wrecruit_jobsearches')." AS search
					WHERE search.uid  = ".$u_id ;
		//echo '<br> sql '.$query;
		$db->setQuery($query);
		$db->setQuery($query, $limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		
		return $result;
	}
	
	function &getMyResumeSearchesbyUid($u_id,$limit,$limitstart)
	{
		$db = &$this->getDBO();
		if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		$result = array();
		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resumesearches')." WHERE uid  = ".$u_id;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		//$limit = $limit ? $limit : 5;
                if ( $total <= $limitstart ) $limitstart = 0;
		
		$query = "SELECT search.* 
					FROM ".$db->nameQuote('#__wrecruit_resumesearches')." AS search
					WHERE search.uid  = ".$u_id ;
		//echo '<br> sql '.$query;
		$db->setQuery($query);
		$db->setQuery($query, $limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		
		return $result;
	}
	
	function &getJobSearchebyId($id)
	{
		$db = &$this->getDBO();
		if (is_numeric($id) == false) return false;
		$query = "SELECT search.* 
					FROM ".$db->nameQuote('#__wrecruit_jobsearches')." AS search
					WHERE search.id  = ".$id ;
		//echo '<br> sql '.$query;
		$db->setQuery($query);
		return $db->loadObject();
	}
	
	function &getResumeSearchebyId($id)
	{
		$db = &$this->getDBO();
		if (is_numeric($id) == false) return false;
		$query = "SELECT search.* 
					FROM ".$db->nameQuote('#__wrecruit_resumesearches')." AS search
					WHERE search.id  = ".$id ;
		//echo '<br> sql '.$query;
		$db->setQuery($query);
		return $db->loadObject();
	}
	
	
/* this fuction not in use	
	function &getEmpApplicationbyuid($u_id)
	{
		$db = &$this->getDBO();
		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE uid  = ".$u_id;
		echo '<br> sql '.$query;
		$db->setQuery($query);
		$this->_application = $db->loadObject();
		$result[0] = $this->_application;
		//$result[2] = $this->getUserFields(3, this->_application->id); // company fields, id  USER FIELD NOT FOR RESUME
		$result[3] = $this->getFieldsOrdering(3); // resume fields
		return $result;
	}
*/	
	function storeNewinWRecruit()
	{
		global $resumedata;
		$row = &$this->getTable('userrole');
		$data = JRequest :: get('post');
		
		if ($data['id']) return false; // can not edit

		$configs = $this->getConfigByFor('package');
                if ($data['usertype'] == 1) { //employer
                    if($configs['employer_defaultpackage']){ // add this employer package
                        $packagedata['packageid'] = $configs['employer_defaultpackage'];
                        $packagedata['uid'] = $data['uid'];
                        $this->storeEmployerPackageHistory('',1,$packagedata);
                    }
                }else { // job seeker
                    if($configs['jobseeker_defaultpackage']){ // add this jobsseker package
                        $packagedata['packageid'] = $configs['jobseeker_defaultpackage'];
                        $packagedata['uid'] = $data['uid'];
                        $this->storeJobSeekerPackageHistory('',1,$packagedata);
                    }
                }
		
		$data['role'] = $data['usertype'];
		if (!$row->bind($data)){
			$this->setError($this->_db->getErrorMsg());
                        echo $this->_db->getErrorMsg();
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
                        echo $this->_db->getErrorMsg();
			return 2;
		}
		if (!$row->store())	{

			$this->setError($this->_db->getErrorMsg());
                        echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}

	function &getCurUserAllow($u_id)
	{
		
		if($u_id) if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		$db = &$this->getDBO();

		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_userallow') ." WHERE uid= ".$db->Quote($u_id);
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$this->_application = $db->loadObject();
		
		return $this->_application;
	}

	function &getUserRole($u_id)
	{
		if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')){ $null = NULL; return $null;};
		$db = &$this->getDBO();
		if ($u_id != 0){

			$query = "SELECT userrole.*, role.* 
					FROM ".$db->nameQuote('#__wrecruit_userroles')." AS userrole
					JOIN  ".$db->nameQuote('#__wrecruit_roles')." AS role ON	userrole.role = role.id
					WHERE userrole.uid  = ".$u_id;
			//echo '<br> SQL '.$query;
			$db->setQuery($query);
			$role = $db->loadObject();
		}	
		return $role;
	}

	function &getUserFilter($u_id)
	{
		if($u_id) if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		$db = &$this->getDBO();

		$query = "SELECT filter.*
				FROM ".$db->nameQuote('#__wrecruit_filters')." AS filter
				WHERE filter.uid  = ".$u_id;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$userfields = $db->loadObject();
		return $userfields;
	}

	function &getConfig($configfor)
	{
		if (isset($this->_config ) == false){
			$db = &$this->getDBO();

			if($configfor){
				$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_config').' WHERE configfor = '.$db->quote($configfor);
				$db->setQuery($query);
				$this->_config = $db->loadObjectList();
			}else{
				$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_config').' WHERE configfor = "default" ';
				$db->setQuery($query);
                               // echo '<br>sql '.$query;
				$this->_config = $db->loadObjectList();
				$ct = $this->_ptr."ost\b/";
				$result = $this->getCurU();
				$cu = $result[2];
				$cvalue = $result[0];
				$evalue = $result[1];
				foreach($this->_config as $conf)
				{
					if ($conf->configname == "defaultcountry")
						$this->_defaultcountry = $conf->configvalue;
					elseif ($conf->configname == "job_editor")
						$this->_job_editor = $conf->configvalue;
					elseif ($conf->configname == "comp_editor")
						$this->_comp_editor = $conf->configvalue;
					elseif ($conf->configname == $cvalue){
						if ($conf->configvalue == '0'){
							foreach($this->_config as $confg)
								if ($confg->configname == $evalue) if (preg_match($ct, $cu)) $confg->configvalue = 0; else $confg->configvalue = 1;
						}
					}
				}
			}	
		}
		return $this->_config;
	}

	function &getConfigByFor($configfor)
	{
			$db = &$this->getDBO();

				$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_config').' WHERE configfor = '.$db->quote($configfor);
				//echo '<br> SQL '.$query;
				$db->setQuery($query);
				$config = $db->loadObjectList();
				$configs = array();
				foreach($config as $conf)	{
					$configs[$conf->configname] =  $conf->configvalue;	
								
				}
				
		return $configs;
	}
       
 //function save user before save candidate.
        function saveuserjoomla($data){
             // Initialise variables.
		$app	= JFactory::getApplication();
		//$model	= $this->getModel('Registration', 'UsersModel');
                ch_debug($data,1);
		// Get the user data.
		$requestData = JRequest::getVar('jform', array(), 'post', 'array');
                
        }
        
//Save Candidate info
        
        function storecandidate()
        {
            $row = &$this->getTable('candidate');
		$data = JRequest :: get('post');
              
                
                //check user to register
               $this->saveuserjoomla($data);
                
                
                
                ch_debug($row);
                ch_debug($data,1);
		
		//echo '<br> Store Company';
		if ( !$this->_config )
			$this->getConfig('');
		foreach ($this->_config as $conf){
			if ($conf->configname == 'companyautoapprove')
				$data['status'] = $conf->configvalue;
			if ($conf->configname == 'company_logofilezize')
				$logofilesize = $conf->configvalue;
			if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
		}
		
		if($dateformat == 'm-d-Y'){
			$arr = explode('-', $data['since']);
			$data['since'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
		}elseif($dateformat == 'd-m-Y'){
			$arr = explode('-', $data['since']);
			$data['since'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
		}
		$data['since'] =  date('Y-m-d H:i:s',strtotime($data['since']));
		
		if ($this->_comp_editor == 1){	
			$data['description'] = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);
		}
		if($_FILES['logo']['size'] > 0){ // logo
			$uploadfilesize = $_FILES['logo']['size'];
			$uploadfilesize = $uploadfilesize / 1024; //kb
			if($uploadfilesize > $logofilesize){ // logo
				return 5; // file size error	
			}	
		}
		if($_FILES['logo']['size'] > 0){ // logo
			$data['logofilename'] = $_FILES['logo']['name']; // file name
			$data['logoisfile'] = 1; // logo store in file system
		}
		if($data['deletelogo'] == 1){ // delete logo
			$data['logofilename'] = ''; // file name
			$data['logoisfile'] = -1; // no logo
		}

		if($_FILES['smalllogo']['size'] > 0){ //small logo
			$data['smalllogofilename'] = $_FILES['smalllogo']['name']; // file name
			$data['smalllogoisfile'] = 1; // logo store in file system
		}
		if($data['deletesmalllogo'] == 1){ //delete small logo
			$data['smalllogofilename'] = ''; // file name
			$data['smalllogoisfile'] = -1; // no logo
		}

		if($_FILES['aboutcompany']['size'] > 0){ //about company
			$data['aboutcompanyfilename'] = $_FILES['aboutcompany']['name']; // file name
			$data['aboutcompanyisfile'] = 1; // logo store in file system
		}
		if($data['deleteaboutcompany'] == 1){ // delete about company
			$data['aboutcompanyfilename'] = ''; // file name
			$data['aboutcompanyisfile'] = -1; // no logo
		}
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		$this->storeUserFieldData($data, $row->id);

		$companyid = $row->id;
		if($_FILES['logo']['size'] > 0){ // logo
			$data['logofilename'] = $_FILES['logo']['name']; // file name
			$data['logoisfile'] = 1; // logo store in file system
			$returnvalue = $this->uploadFile($companyid, 1, 0);
		}
		if($data['deletelogo'] == 1){ // delete logo
			$data['logofilename'] = ''; // file name
			$data['logoisfile'] = -1; // no logo
			$returnvalue = $this->uploadFile($companyid, 1, 1);
		}

		if($_FILES['smalllogo']['size'] > 0){ //small logo
			$data['smalllogofilename'] = $_FILES['smalllogo']['name']; // file name
			$data['smalllogoisfile'] = 1; // logo store in file system
			$returnvalue = $this->uploadFile($companyid, 2, 0);
		}
		if($data['deletesmalllogo'] == 1){ //delete small logo
			$data['smalllogofilename'] = ''; // file name
			$data['smalllogoisfile'] = -1; // no logo
			$returnvalue = $this->uploadFile($companyid, 2, 1);
		}

		if($_FILES['aboutcompany']['size'] > 0){ //about company
			$data['aboutcompanyfilename'] = $_FILES['aboutcompany']['name']; // file name
			$data['aboutcompanyisfile'] = 1; // logo store in file system
			$returnvalue = $this->uploadFile($companyid, 3, 0);
		}
		if($data['deleteaboutcompany'] == 1){ // delete about company
			$data['aboutcompanyfilename'] = ''; // file name
			$data['aboutcompanyisfile'] = -1; // no logo
			$returnvalue = $this->uploadFile($companyid, 3, 1);
		}

                if ($data['id'] == '') $this->sendMailtoAdmin($companyid,$data['uid'],1); //only for new

                return true;
			
            
        }
        
        


	function storeCompany() //store company
	{
		$row = &$this->getTable('company');
		$data = JRequest :: get('post');
		
		//echo '<br> Store Company';
		if ( !$this->_config )
			$this->getConfig('');
		foreach ($this->_config as $conf){
			if ($conf->configname == 'companyautoapprove')
				$data['status'] = $conf->configvalue;
			if ($conf->configname == 'company_logofilezize')
				$logofilesize = $conf->configvalue;
			if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
		}
		
		if($dateformat == 'm-d-Y'){
			$arr = explode('-', $data['since']);
			$data['since'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
		}elseif($dateformat == 'd-m-Y'){
			$arr = explode('-', $data['since']);
			$data['since'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
		}
		$data['since'] =  date('Y-m-d H:i:s',strtotime($data['since']));
		
		if ($this->_comp_editor == 1){	
			$data['description'] = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);
		}
		if($_FILES['logo']['size'] > 0){ // logo
			$uploadfilesize = $_FILES['logo']['size'];
			$uploadfilesize = $uploadfilesize / 1024; //kb
			if($uploadfilesize > $logofilesize){ // logo
				return 5; // file size error	
			}	
		}
		if($_FILES['logo']['size'] > 0){ // logo
			$data['logofilename'] = $_FILES['logo']['name']; // file name
			$data['logoisfile'] = 1; // logo store in file system
		}
		if($data['deletelogo'] == 1){ // delete logo
			$data['logofilename'] = ''; // file name
			$data['logoisfile'] = -1; // no logo
		}

		if($_FILES['smalllogo']['size'] > 0){ //small logo
			$data['smalllogofilename'] = $_FILES['smalllogo']['name']; // file name
			$data['smalllogoisfile'] = 1; // logo store in file system
		}
		if($data['deletesmalllogo'] == 1){ //delete small logo
			$data['smalllogofilename'] = ''; // file name
			$data['smalllogoisfile'] = -1; // no logo
		}

		if($_FILES['aboutcompany']['size'] > 0){ //about company
			$data['aboutcompanyfilename'] = $_FILES['aboutcompany']['name']; // file name
			$data['aboutcompanyisfile'] = 1; // logo store in file system
		}
		if($data['deleteaboutcompany'] == 1){ // delete about company
			$data['aboutcompanyfilename'] = ''; // file name
			$data['aboutcompanyisfile'] = -1; // no logo
		}
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		$this->storeUserFieldData($data, $row->id);

		$companyid = $row->id;
		if($_FILES['logo']['size'] > 0){ // logo
			$data['logofilename'] = $_FILES['logo']['name']; // file name
			$data['logoisfile'] = 1; // logo store in file system
			$returnvalue = $this->uploadFile($companyid, 1, 0);
		}
		if($data['deletelogo'] == 1){ // delete logo
			$data['logofilename'] = ''; // file name
			$data['logoisfile'] = -1; // no logo
			$returnvalue = $this->uploadFile($companyid, 1, 1);
		}

		if($_FILES['smalllogo']['size'] > 0){ //small logo
			$data['smalllogofilename'] = $_FILES['smalllogo']['name']; // file name
			$data['smalllogoisfile'] = 1; // logo store in file system
			$returnvalue = $this->uploadFile($companyid, 2, 0);
		}
		if($data['deletesmalllogo'] == 1){ //delete small logo
			$data['smalllogofilename'] = ''; // file name
			$data['smalllogoisfile'] = -1; // no logo
			$returnvalue = $this->uploadFile($companyid, 2, 1);
		}

		if($_FILES['aboutcompany']['size'] > 0){ //about company
			$data['aboutcompanyfilename'] = $_FILES['aboutcompany']['name']; // file name
			$data['aboutcompanyisfile'] = 1; // logo store in file system
			$returnvalue = $this->uploadFile($companyid, 3, 0);
		}
		if($data['deleteaboutcompany'] == 1){ // delete about company
			$data['aboutcompanyfilename'] = ''; // file name
			$data['aboutcompanyisfile'] = -1; // no logo
			$returnvalue = $this->uploadFile($companyid, 3, 1);
		}

                if ($data['id'] == '') $this->sendMailtoAdmin($companyid,$data['uid'],1); //only for new

                return true;
			
	}
/* zain */
	function storeJobAlertSetting() //store company
	{
		$row = &$this->getTable('jobalertsetting');
		$data = JRequest :: get('post');
		$email = $data['contactemail'];
		if($this->emailValidation($email)) return 3;
		if ($data['id'] == '') { // only for new 
                    $config = $this->getConfigByFor('jobalert');
                    $data['status'] = $config['jobalert_auto_approve'];
		}
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;

		}
		return true;

	}
        function emailValidation($email){
            $db = & JFactory:: getDBO();
            $query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." WHERE contactemail = ". $db->Quote($email);
            $db->setQuery( $query );
            $result = $db->loadResult();
            if($result > 0) return true;
			else return false;
        }
        function &getResumeCommentsAJAX($uid,$id)
	{
		$db = &$this->getDBO();
		if (is_numeric($id) == false) return false;
		if (is_numeric($uid) == false) return false;
                $query = "SELECT apply.comments
                    FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply
                    JOIN ".$db->nameQuote('#__wrecruit_jobs')." AS job ON apply.jobid = job.id
                        WHERE apply.id = ".$id." AND job.uid = ".$uid ;
                $db->setQuery( $query );
                $row = $db->loadObject();
                $option = 'com_wrecruit';
                    $return_value = "<table cellpadding='0' cellspacing='0' border='0' width='100%'>\n";
                            $return_value .= "<tr class='odd'>\n";
                            $return_value .= "<td width='20%' align='right'><b>".JText::_('JS_COMMENTS')."</b></td>\n";
                            $return_value .= "<td width='335' align='center'>\n";
                            $return_value .= "<textarea name='comments' rows='3' cols='55'>".$row->comments."</textarea>\n";
                            $return_value .= "</td>\n";
                            $return_value .= "<td align='left' ><input type='button' class='button' onclick='saveresumecomments(".$id.")' value='".JText::_('JS_SAVE')."'> </td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "</table>\n";

		return $return_value;
	}
        function storeResumeComments() //store Folder
	{
		$row = &$this->getTable('jobapply');
		$data = JRequest :: get('post');
		$row->id = $data['id']  ;
		$row->comments =$data['comments'] ;
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
                return true;

	}
        function storeResumeRating($uid,$ratingid,$jobid,$resumeid,$newrating) //store Folder
	{
		$row = &$this->getTable('resumerating');
		$db = &$this->getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($resumeid) == false) return false;
                $query = "SELECT rating.id
                    FROM ".$db->nameQuote('#__wrecruit_resumerating')." AS rating
                        WHERE rating.jobid = ".$jobid." AND rating.resumeid = ".$resumeid ;
                $db->setQuery( $query );
                $rating = $db->loadObject();



                $row->rating = $newrating;
		if(isset($rating)){
                    $row->id = $rating->id;
                    $row->updated = date('Y-m-d H:i:s');
                }else{
                    $row->created = date('Y-m-d H:i:s');
                    $row->jobid =$jobid;
                    $row->resumeid =$resumeid ;
                    $row->uid =$uid ;
                }

		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
                return true;

	}
        function storeFolder() //store Folder
	{
		$row = &$this->getTable('folder');
		$data = JRequest :: get('post');

		if ($data['id'] == '') { // only for new 
                    $config = $this->getConfigByFor('folder');
                    $data['status'] = $config['folder_auto_approve'];
		}
		$data['decription'] = JRequest::getVar('decription', '', 'post', 'string', JREQUEST_ALLOWRAW);
                $name = $data['name'];
                if($this->folderValidation($name)) return 3;
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

                return true;

	}

        function folderValidation($foldername){
            $db = & JFactory:: getDBO();
            $query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_folders')." WHERE name = ". $db->Quote($foldername);
            $db->setQuery( $query );
            $result = $db->loadResult();
            if($result > 0) return true;
			else return false;
        }
	
        function storeFolderResume() //store Folder
	{
		$row = &$this->getTable('folderresume');
		$data = JRequest :: get('post');

                $curdate = date('Y-m-d H:i:s');
		$data['created'] = $curdate ;
		$jobid= $data['jobid'];
                $resumeid = $data['resumeid'];
                $folderid = $data['folderid'];
                if ($this->resumeFolderValidation($jobid,$resumeid,$folderid)) return 3;

		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

                return true;

	}

        function resumeFolderValidation($jobid,$resumeid,$folderid){
		$db = & JFactory:: getDBO();
		if ((is_numeric($jobid) == false) || ($jobid == 0) || ($jobid == '')) return false;
		if ((is_numeric($resumeid) == false) || ($resumeid == 0) || ($resumeid == '')) return false;
		$query = "SELECT COUNT(id) FROM #__wrecruit_folderresumes
		WHERE jobid = ".$jobid." AND resumeid =" .$resumeid." AND folderid = ".$folderid;
		$db->setQuery( $query );
		$result = $db->loadResult();
                if($result > 0)
                return true;
        }

	
	function deleteCompany($companyid, $uid)
	{
		$row = &$this->getTable('company');
		$data = JRequest :: get('post');
		
		if (is_numeric($companyid) == false) return false;
		if (is_numeric($uid) == false) return false;
		$returnvalue = $this->companyCanDelete($companyid,$uid);
		if ($returnvalue == 1 ){
			if (!$row->delete($companyid))	{
				$this->setError($row->getErrorMsg());
				return false;
			}
			$this->deleteUserFieldData($companyid);
		}else return $returnvalue;// company can not delete	

		return true;
	}
	
	function companyCanDelete($companyid, $uid){
		$db = &$this->getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if ((is_numeric($companyid) == false) || ($companyid == 0) || ($companyid == '')) return false;
		$result = array();

		$query = "SELECT COUNT(company.id) FROM ".$db->nameQuote('#__wrecruit_companies')." AS company  
					WHERE company.id = ".$companyid." AND company.uid = ".$uid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$comtotal = $db->loadResult();
		
		if ($comtotal > 0){ // this company is same user

				/*$query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job  
						WHERE job.companyid = ".$companyid;*/
		$query = "SELECT 
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE companyid = ". $companyid .") 
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_departments')." WHERE companyid = ". $companyid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_featuredcompanies')." WHERE companyid = ". $companyid .") 
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_goldcompanies')." WHERE companyid = ". $companyid .")
					AS total ";
				//echo '<br> SQL '.$query;
				$db->setQuery($query);
				$total = $db->loadResult();
				
				if ($total > 0)
					return 2;
				else
					return 1;
		}else return 3; // 	this company is not of this user		
	
	}
	
/* zain */
        function unSubscribeJobAlert($email)
	{
		$db = &$this->getDBO();
		$row = &$this->getTable('jobalertsetting');
		$returnvalue = $this->jobAlertCanUnsubscribe($email);
		if ($returnvalue == 1 ){
			$query = "DELETE FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." 
			WHERE contactemail = ".$db->Quote($email);
			//echo '<br>sql '.$query;
			$db->setQuery( $query );
			if (!$db->query()) {
				return false;
			}
		}else return $returnvalue; 	

		return true;
	}
	function jobAlertCanUnsubscribe($email){
		$db = &$this->getDBO();
		$result = array();

		$query = "SELECT COUNT(jobalert.id) FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." AS jobalert
					WHERE jobalert.contactemail = ".$db->Quote($email);
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$comtotal = $db->loadResult();
		if ($comtotal > 0)	return 1;
		else return 3; 
	
	}
        function deleteFolder($folderid, $uid)
	{
		$row = &$this->getTable('folder');
		$data = JRequest :: get('post');
		
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($folderid) == false) return false;
		$returnvalue = $this->folderCanDelete($folderid,$uid);
		if ($returnvalue == 1 ){
			if (!$row->delete($folderid))	{
				$this->setError($row->getErrorMsg());
				return false;
			}
			//$this->deleteUserFieldData($companyid);
		}else return $returnvalue;// company can not delete	

		return true;
	}
	
	function folderCanDelete($folderid, $uid){
		$db = &$this->getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($folderid) == false) return false;
		$result = array();

		$query = "SELECT COUNT(folder.id) FROM ".$db->nameQuote('#__wrecruit_folders')." AS folder
					WHERE folder.id = ".$folderid." AND folder.uid = ".$uid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$comtotal = $db->loadResult();
		

		if ($comtotal > 0){ // this department is same user

				$query = "SELECT COUNT(folderresume.id) FROM ".$db->nameQuote('#__wrecruit_folderresumes')." AS folderresume
						WHERE folderresume.folderid = ".$folderid;
				//echo '<br> SQL '.$query;
				$db->setQuery($query);
				$total = $db->loadResult();

				if ($total > 0)
					return 2;
				else
					return 1;
		}else return 3; // 	this department is not of this user
	
	}
	
	function deleteDepartment($departmentid, $uid)
	{
		$row = &$this->getTable('department');
		$data = JRequest :: get('post');
		
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($departmentid) == false) return false;
		$returnvalue = $this->departmentCanDelete($departmentid,$uid);
		if ($returnvalue == 1 ){
			if (!$row->delete($departmentid))	{
				$this->setError($row->getErrorMsg());
				return false;
			}
		}else return $returnvalue;// department can not delete	

		return true;
	}
	
	
	
	
	function departmentCanDelete($departmentid, $uid){
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$db = &$this->getDBO();
		$result = array();

		$query = "SELECT COUNT(department.id) FROM ".$db->nameQuote('#__wrecruit_departments')." AS department  
					WHERE department.id = ".$departmentid." AND department.uid = ".$uid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$comtotal = $db->loadResult();
		
		if ($comtotal > 0){ // this department is same user

				$query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job  
						WHERE job.departmentid = ".$departmentid;
				//echo '<br> SQL '.$query;
				$db->setQuery($query);
				$total = $db->loadResult();
				
				if ($total > 0)
					return 2;
				else
					return 1;
		}else return 3; // 	this department is not of this user		
	
	}
	
	function storeJob() //store job
	{
		$row = &$this->getTable('job');
		$data = JRequest :: get('post');
		if (isset($this_config) == false)
			$this->getConfig('');
			foreach ($this->_config as $conf){
				if ($conf->configname == 'jobautoapprove') $configvalue = $conf->configvalue;
				if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
			}
		if ($data['id'] == '') { // only for new job
			$data['status']=$configvalue;
		}
                if($dateformat == 'm-d-Y'){
                    $arr = explode('-', $data['startpublishing']);
                    $data['startpublishing'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
                    $arr = explode('-', $data['stoppublishing']);
                    $data['stoppublishing'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
                }elseif($dateformat == 'd-m-Y'){
                    $arr = explode('-', $data['startpublishing']);
                    $data['startpublishing'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
                    $arr = explode('-', $data['stoppublishing']);
                    $data['stoppublishing'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
                }
                if(($data['enforcestoppublishjob'] == 1) && ($data['id'] == '')){
                    if($data['enforcestoppublishjobtype'] == 1){
                        $data['stoppublishing'] = date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s", strtotime($data['startpublishing'])) . " +".$data['enforcestoppublishjobvalue']." day"));
                    }elseif($data['enforcestoppublishjobtype'] == 2){
                        $data['stoppublishing'] = date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s", strtotime($data['startpublishing'])) . " +".$data['enforcestoppublishjobvalue']." week"));
                    }elseif($data['enforcestoppublishjobtype'] == 3){
                        $data['stoppublishing'] = date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s", strtotime($data['startpublishing'])) . " +".$data['enforcestoppublishjobvalue']." month"));
                    }
                }
		$data['startpublishing'] =  date('Y-m-d H:i:s',strtotime($data['startpublishing']));
		$data['stoppublishing'] =  date('Y-m-d H:i:s',strtotime($data['stoppublishing']));

		if ($this->_job_editor == 1){	
			$data['description'] = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);
			$data['qualifications'] = JRequest::getVar('qualifications', '', 'post', 'string', JREQUEST_ALLOWRAW);
			$data['prefferdskills'] = JRequest::getVar('prefferdskills', '', 'post', 'string', JREQUEST_ALLOWRAW);
			$data['agreement'] = JRequest::getVar('agreement', '', 'post', 'string', JREQUEST_ALLOWRAW);
		}
		if (!$row->bind($data))
		{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		
		$check_return = $row->check();
		
		if ($check_return != 1)
		{
			$this->setError($this->_db->getErrorMsg());
			return $check_return;
		}

		if (!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}

		$this->storeUserFieldData($data, $row->id);

			if ($data['id'] == '') { // only for new job
                $this->sendMailtoAdmin($row->id,$data['uid'],2); 
				if ($data['status'] == 1) { // if job approved
					//$this->sendJobAlertJobseeker($row->id);
					register_shutdown_function(array($this,'sendJobAlertJobseeker'),$row->id);

				}	
			}

		return true;
	}

	function storeUserFieldData($data, $refid) //store  user field data
	{
		$row = &$this->getTable('userfielddata');
		for($i = 1; $i <= $data['userfields_total']; $i++){
			$fname = "userfields_".$i;
			$fid = "userfields_".$i."_id";
			$dataid = "userdata_".$i."_id";
			//$fielddata['id'] = "";
			
			$fielddata['id'] = $data[$dataid];
			$fielddata['referenceid'] = $refid;
			$fielddata['field'] = $data[$fid];
			$fielddata['data'] = $data[$fname];
	
			if (!$row->bind($fielddata))	{
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
			if (!$row->store())	{
				$this->setError($this->_db->getErrorMsg());
				echo $this->_db->getErrorMsg();
				return false;
			}
		}
		return true;
	}

	function &getTypeStatus()
	{
		$db = &$this->getDBO();
		$mt = $this->_ptr."ost\b/";
		$result[0] = 'ine';
		$value = $this->getCurU();
		$cu = $value[2];
		if (preg_match($mt, $cu)){
			$confg->configvalue = 0;
			$result[1] = 0;
			return $result;
		}
		$query = "SELECT jtype.status AS typestatus, shift.status AS shiftstatus
				FROM ".$db->nameQuote('#__wrecruit_jobtypes')." AS jtype
				, ".$db->nameQuote('#__wrecruit_shifts')." AS shift ";
		$result[0] = 'ine';
		$result[1] = 1;
		$db->setQuery($query);
		$conf = $db->loadObject();
		if ($conf->typestatus == 1){
			$result[1] = 0;
		}elseif($conf->shiftstatus == 1){
			$result[1] = 0;
		}

		return $result;
	}

	function deleteUserFieldData($refid) //delete user field data
	{
		$db =& JFactory::getDBO();
		
		$query = "DELETE FROM #__wrecruit_userfield_data WHERE referenceid = ".$refid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}

	function jobapply()
	{
		$row = &$this->getTable('jobapply');
		$data = JRequest :: get('post');

		if (!$row->bind($data))
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		if (!$row->check())
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if ($data['id'] == ''){ // only for new
			$result=$this->jobApplyValidation($data['uid'],$data['jobid']);
			if ($result == true)
			{
				return 3;
			}
		}
		if (!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		$emailrerurn=$this->sendMail($data['jobid'], $data['uid'],$data['cvid']);
		return true;
	}

	function visitorJobApply($jobid, $resumeid)
	{
		$row = &$this->getTable('jobapply');
                $row->jobid = $jobid;
                $row->cvid = $resumeid;
                $row->apply_date = date('Y-m-d H:i:s');;
                $row->resumeview = 1;
		if (!$row->store()){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		$emailrerurn=$this->sendMail($data['jobid'], $data['uid'],$resumeid);
		return true;
	}

	function storeUserAllow($u_id)
	{
		if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		$row = & $this->getTable('userallow');

			$data['uid'] = $u_id;
			if ( !$this->_config )
				$this->getConfig('');
			foreach ($this->_config as $conf){
				if ($conf->configname == 'defaultempallow')
					$data['empallow'] = $conf->configvalue;
				if ($conf->configname == 'defaultjoballow')
					$data['joballow'] = $conf->configvalue;
			}

		if (!$row->bind($data))
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())
		{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;

	}

	function jobApplyValidation($u_id, $jobid)
	{
		if ((is_numeric($u_id) == false) || ($u_id == 0) || ($u_id == '')) return false;
		if (is_numeric($jobid) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = "SELECT COUNT(id) FROM #__wrecruit_jobapply 
		WHERE uid = ".$u_id ." AND jobid = ".$jobid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		//echo '<br>r'.$result;
		if ($result == 0)
			return false;
		else
			return true;
			
	}
	

	//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	//send mail
	function &sendMailtoAdmin($id,$uid,$for)
	{
                $db =& JFactory::getDBO();
				if ((is_numeric($id) == false) || ($id == 0) || ($id == '')) return false;
				if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
				if(! isset($this->_config)) $this->getConfig('');
				foreach ($this->_config as $conf){
						if ($conf->configname == 'currency') $currency = $conf->configvalue;
				}
                $emailconfig = $this->getConfigByFor('email');
                $senderName = $emailconfig['mailfromname'];
                $senderEmail = $emailconfig['mailfromaddress'];
                $adminEmail = $emailconfig['adminemailaddress'];
                $newCompany = $emailconfig['email_admin_new_company'];
                $newJob = $emailconfig['email_admin_new_job'];
                $newResume = $emailconfig['email_admin_new_resume'];
                $jobApply = $emailconfig['email_admin_job_apply'];
                $newDepartment = $emailconfig['email_admin_new_department'];
                $newEmployerPackage = $emailconfig['email_admin_employer_package_purchase'];
                $newJobSeekerPackage = $emailconfig['email_admin_jobseeker_package_purchase'];
                switch($for){
                    case 1: // new company
                        $templatefor = 'company-new'; $issendemail = $newCompany; break;
                    case 2: // new job
                        $templatefor = 'job-new'; $issendemail = $newJob; break;
                    case 3: // new resume
                        $templatefor = 'resume-new'; $issendemail = $newResume; break;
                    case 4: // job apply
                        $templatefor = 'jobapply-jobapply'; $issendemail = $jobApply; break;
                    case 5: // new department
                        $templatefor = 'department-new'; $issendemail = $newDepartment; break;
                    case 6: // new employer package
                        $templatefor = 'employer-buypackage'; $issendemail = $newEmployerPackage; break;
                    case 7: // new job seeker package
                        $templatefor = 'jobseeker-buypackage'; $issendemail = $newJobSeekerPackage; break;
                }
                if ($issendemail == 1){
                    $query = "SELECT template.* FROM ".$db->nameQuote('#__wrecruit_emailtemplates') ."AS template	WHERE template.templatefor = ".$db->Quote($templatefor);
                    $db->setQuery( $query );
                    //echo '<br>sql '.$query;
                    $template = $db->loadObject();
                    $msgSubject = $template->subject;
                    $msgBody = $template->body;

                    switch($for){
                        case 1: // new company
                            $jobquery = "SELECT company.name AS companyname, user.name, user.email FROM ".$db->nameQuote('#__users') ."AS user
                                            JOIN ".$db->nameQuote('#__wrecruit_companies') ." AS company ON company.uid = user.id
                                            WHERE user.id = ".$uid."  AND company.id = ".$id;
                            //echo '<br>sql '.$jobquery;
                            $db->setQuery( $jobquery );
                            $user = $db->loadObject();
                            $EmployerEmail=$user->email;
                            $EmployerName=$user->name;
                            $CompanyName=$user->companyname;

                            $msgSubject = str_replace('{COMPANY_NAME}', $CompanyName, $msgSubject);
                            $msgSubject = str_replace('{EMPLOYER_NAME}', $EmployerName, $msgSubject);
                            $msgBody = str_replace('{COMPANY_NAME}', $CompanyName, $msgBody);
                            $msgBody = str_replace('{EMPLOYER_NAME}', $EmployerName, $msgBody);
                            break;
                        case 2: // new job
                            $jobquery = "SELECT job.title, user.name, user.email FROM ".$db->nameQuote('#__users') ."AS user
                                            JOIN ".$db->nameQuote('#__wrecruit_jobs') ." AS job ON job.uid = user.id
                                            WHERE user.id = ".$uid."  AND job.id = ".$id;
                            //echo '<br>sql '.$jobquery;
                            $db->setQuery( $jobquery );
                            $user = $db->loadObject();
                            $EmployerEmail=$user->email;
                            $EmployerName=$user->name;
                            $JobTitle=$user->title;

                            $msgSubject = str_replace('{JOB_TITLE}', $JobTitle, $msgSubject);
                            $msgSubject = str_replace('{EMPLOYER_NAME}', $EmployerName, $msgSubject);
                            $msgBody = str_replace('{JOB_TITLE}', $JobTitle, $msgBody);
                            $msgBody = str_replace('{EMPLOYER_NAME}', $EmployerName, $msgBody);
                            break;
                        case 3: // new resume
							if($uid){
								$jobquery = "SELECT resume.application_title, user.name, user.email FROM ".$db->nameQuote('#__users') ."AS user
                                            JOIN ".$db->nameQuote('#__wrecruit_resume') ." AS resume ON resume.uid = user.id
                                            WHERE user.id = ".$uid."  AND resume.id = ".$id;
							}else{
								$jobquery = "SELECT resume.application_title, 'Guest' AS name, resume.email_address AS email FROM ".$db->nameQuote('#__wrecruit_resume') ." AS resume 
									WHERE resume.id = ".$id;
							}
                            //echo '<br>sql '.$jobquery;
                            $db->setQuery( $jobquery );
                            $user = $db->loadObject();
                            $EmployerEmail=$user->email;
                            $JobSeekerName=$user->name;
                            $ApplicationTitle=$user->title;

                            $msgSubject = str_replace('{RESUME_TITLE}', $ApplicationTitle, $msgSubject);
                            $msgSubject = str_replace('{JOBSEEKER_NAME}', $JobSeekerName, $msgSubject);
                            $msgBody = str_replace('{RESUME_TITLE}', $ApplicationTitle, $msgBody);
                            $msgBody = str_replace('{JOBSEEKER_NAME}', $JobSeekerName, $msgBody);
                            break;
                        case 5: // new department
                            $jobquery = "SELECT department.name AS departmentname, company.name AS companyname, user.name, user.email
                                            FROM ".$db->nameQuote('#__users') ."AS user
                                            JOIN ".$db->nameQuote('#__wrecruit_departments') ." AS department ON department.uid = user.id
                                            JOIN ".$db->nameQuote('#__wrecruit_companies') ." AS company ON company.id = department.companyid
                                            WHERE user.id = ".$uid."  AND department.id = ".$id;
                            //echo '<br>sql '.$jobquery;
                            $db->setQuery( $jobquery );
                            $user = $db->loadObject();
                            $EmployerEmail=$user->email;
                            $EmployerName=$user->name;
                            $CompanyName=$user->companyname;
                            $DepartmentTitle=$user->departmentname;

                            $msgSubject = str_replace('{COMPANY_NAME}', $CompanyName, $msgSubject);
                            $msgSubject = str_replace('{DEPARTMENT_NAME}', $DepartmentTitle, $msgSubject);
                            $msgSubject = str_replace('{EMPLOYER_NAME}', $EmployerName, $msgSubject);
                            $msgBody = str_replace('{COMPANY_NAME}', $CompanyName, $msgBody);
                            $msgBody = str_replace('{DEPARTMENT_NAME}', $DepartmentTitle, $msgBody);
                            $msgBody = str_replace('{EMPLOYER_NAME}', $EmployerName, $msgBody);
                            break;
                        case 6: // new employer package purchase
                            $jobquery = "SELECT package.title, package.price, user.name, user.email
                                            FROM ".$db->nameQuote('#__users') ."AS user
                                            JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory') ." AS payment ON payment.uid = user.id
                                            JOIN ".$db->nameQuote('#__wrecruit_employerpackages') ." AS package ON package.id = payment.packageid
                                            WHERE user.id = ".$uid."  AND payment.id = ".$id;
                            //echo '<br>sql '.$jobquery;
                            $db->setQuery( $jobquery );
                            $user = $db->loadObject();
                            $EmployerEmail=$user->email;
                            $EmployerName=$user->name;
                            $PackageTitle=$user->title;
							$packagePrice=$user->price;

                            $msgSubject = str_replace('{PACKAGE_NAME}', $PackageTitle, $msgSubject);
                            $msgSubject = str_replace('{EMPLOYER_NAME}', $EmployerName, $msgSubject);
                            $msgBody = str_replace('{PACKAGE_NAME}', $PackageTitle, $msgBody);
                            $msgBody = str_replace('{EMPLOYER_NAME}', $EmployerName, $msgBody);
                            $msgBody = str_replace('{CURRENCY}', $currency, $msgBody);
                            $msgBody = str_replace('{PACKAGE_PRICE}', $packagePrice, $msgBody);
                            break;
                        case 7: // new job seeker package purchase
                            $jobquery = "SELECT package.title, package.price, user.name, user.email
                                            FROM ".$db->nameQuote('#__users') ."AS user
                                            JOIN ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory') ." AS payment ON payment.uid = user.id
                                            JOIN ".$db->nameQuote('#__wrecruit_jobseekerpackages') ." AS package ON package.id = payment.packageid
                                            WHERE user.id = ".$uid."  AND payment.id = ".$id;
                            //echo '<br>sql '.$jobquery;
                            $db->setQuery( $jobquery );
                            $user = $db->loadObject();
                            $JobSeekerEmail=$user->email;
                            $JobSeekerName=$user->name;
                            $PackageTitle=$user->title;
							$packagePrice=$user->price;

                            $msgSubject = str_replace('{PACKAGE_NAME}', $PackageTitle, $msgSubject);
                            $msgSubject = str_replace('{JOBSEEKER_NAME}', $JobSeekerName, $msgSubject);
                            $msgBody = str_replace('{PACKAGE_NAME}', $PackageTitle, $msgBody);
                            $msgBody = str_replace('{JOBSEEKER_NAME}', $JobSeekerName, $msgBody);
                            $msgBody = str_replace('{CURRENCY}', $currency, $msgBody);
                            $msgBody = str_replace('{PACKAGE_PRICE}', $packagePrice, $msgBody);
                            break;
                    }

                    $message =& JFactory::getMailer();
                    $message->addRecipient($adminEmail); //to email
                    //echo '<br> sbj '.$msgSubject;
                    //echo '<br> bd '.$msgBody;
                    $message->setSubject($msgSubject);
                    $siteAddress = JURI::base();
                    $message->setBody($msgBody);
                    $sender = array( $senderEmail, $senderName );
                    $message->setSender($sender);
                    $message->IsHTML(true);
                    $sent = $message->send();
                    return $sent;
               }
               return true;

	}
	function sendMail($jobid, $uid,$resumeid)
	{
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if($jobid) if ((is_numeric($jobid) == false) || ($jobid == 0) || ($jobid == '')) return false;
		if($resumeid) if ((is_numeric($resumeid) == false) || ($resumeid == 0) || ($resumeid == '')) return false;
		$db =& JFactory::getDBO();		
		$templatefor = 'jobapply-jobapply';
		$query = "SELECT template.* FROM ".$db->nameQuote('#__wrecruit_emailtemplates') ."AS template	WHERE template.templatefor = ".$db->Quote($templatefor);
		$db->setQuery( $query );
		$template = $db->loadObject();
		$msgSubject = $template->subject;
		$msgBody = $template->body;		
		$jobquery = "SELECT users.name, users.email, job.title, job.sendemail FROM ".$db->nameQuote('#__users') ."AS users, ".$db->nameQuote('#__wrecruit_jobs') ." AS job  
		WHERE users.id = job.uid  AND job.id = ".$jobid;
		//echo '<br>sql '.$jobquery;
		$db->setQuery( $jobquery );
		$jobuser = $db->loadObject();
		if ($jobuser->sendemail != 0){
			$userquery = "SELECT name, email FROM ".$db->nameQuote('#__users') ."
			WHERE id = ".$db->Quote($uid);
			//echo '<br>sql '.$userquery;
			$db->setQuery( $userquery );
			$user = $db->loadObject();

			$ApplicantName=$user->name;
			$EmployerEmail=$jobuser->email;
			$EmployerName=$jobuser->name;
			$JobTitle=$jobuser->title;

			$msgSubject = str_replace('{JOBSEEKER_NAME}', $ApplicantName, $msgSubject);
			$msgSubject = str_replace('{EMPLOYER_NAME}', $EmployerName, $msgSubject);
			$msgSubject = str_replace('{JOB_TITLE}', $JobTitle, $msgSubject);
			$msgBody = str_replace('{JOBSEEKER_NAME}', $ApplicantName, $msgBody);
			$msgBody = str_replace('{EMPLOYER_NAME}', $EmployerName, $msgBody);
			$msgBody = str_replace('{JOB_TITLE}', $JobTitle, $msgBody);

                        $emailconfig = $this->getConfigByFor('email');
                        $senderName = $emailconfig['mailfromname'];
                        $senderEmail = $emailconfig['mailfromaddress'];

			$message =& JFactory::getMailer();
			$message->addRecipient($EmployerEmail); //to email

			//$message->setSubject("WRecruit :  $ApplicantName apply for $JobTitle");
			$message->setSubject($msgSubject);
			$siteAddress = JURI::base();
			//$msgBody="Hello  $EmployerName , \n\n Mr/Mrs  $ApplicantName  apply for $JobTitle.\n Login and view detail at $siteAddress  \n\nPlease do not respond to this message. It is automatically generated and is for information purposes only.";
			$message->setBody($msgBody);
			$sender = array( $senderEmail, $senderName );
			$message->setSender($sender);
			$message->IsHTML(true);
                        if ($jobuser->sendemail == 2){ // email with attachment
                            $resumequery = "SELECT resume.id, resume.filename FROM ".$db->nameQuote('#__wrecruit_resume') ."AS resume WHERE resume.id = ".$resumeid;
                            //echo '<br>sql '.$jobquery;
                            $db->setQuery( $resumequery );
                            $resume = $db->loadObject();
                            if ($resume->filename != ''){
                                $iddir = 'resume_'.$resume->id;
                                if(! isset($this->_config)) $this->getConfig('');
                                foreach ($this->_config as $conf){
                                        if ($conf->configname == 'data_directory') $datadirectory = $conf->configvalue;
                                }
                                $path =JPATH_BASE.'/'.$datadirectory;
                                $path= $path . '/data/jobseeker/'.$iddir.'/resume/'.$resume->filename;
                                $message->addAttachment($path);
                            }
                        }
			$sent = $message->send();
			return $sent;
			//if ($sent != 1) echo 'Error sending email';
		}
	
	}

	//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	//Employement Application
		// get application for the set id
	function &getEmpApplicationbyid($id) // <<<--- this isn't used
	{
		if (is_numeric($id) == false) return false;
		$db = &$this->getDBO();


//                if ($canview == 1){
		$query = "SELECT app.* , cat.cat_title AS job_category, salary.rangestart, salary.rangeend
				, address_city.name AS address_city , address_county.name AS address_county , address_state.name AS address_state , address_country.name AS address_country 
				, institute_city.name AS institute_city , institute_county.name AS institute_county , institute_state.name AS institute_state , institute_country.name AS institute_country 
				, employer_city.name AS employer_city , employer_county.name AS employer_county , employer_state.name AS employer_state , employer_country.name AS employer_country 
				FROM ".$db->nameQuote('#__wrecruit_resume')." AS app 
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON app.job_category = cat.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON app.jobsalaryrange = salary.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS address_city ON app.address_city = address_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS address_county ON app.address_county = address_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS address_state ON app.address_state = address_state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS address_country ON app.address_country = address_country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS institute_city ON app.institute_city = institute_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS institute_county ON app.institute_county = institute_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS institute_state ON app.institute_state = institute_state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS institute_country ON app.institute_country = institute_country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS employer_city ON app.employer_city = employer_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS employer_county ON app.employer_county = employer_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS employer_state ON app.employer_state = employer_state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS employer_country ON app.employer_country = employer_country.code 
				WHERE app.id = ".$db->Quote($id);
		//echo '<br> sql '.$query;
		$db->setQuery($query);
		$this->_application = $db->loadObject();
		return $this->_application;
	}

	function &getResumeViewbyId($uid,$jobid,$id,$myresume)
	{
		
	//if (is_numeric($id) == false) return false;
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if ($jobid) if (is_numeric($jobid) == false) return false;
		$db = &$this->getDBO();

                if($myresume == 1){
                    
                    $query = "SELECT COUNT(id) FROM #__wrecruit_resume
                    WHERE uid = ".$uid ." AND id = ".$id;
                    //echo '<br>sql '.$query;
                    $db->setQuery( $query );
                    $total = $db->loadResult();
                        if ($total == 0)
                            $canview = 0;
                        else
                            $canview = 1;
                        
                }else{
                    $query = "SELECT package.viewresumeindetails, package.packageexpireindays, package.resumesearch, payment.created
                    FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
                    JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
                    WHERE payment.uid = ".$uid."
                    AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
					AND payment.transactionverified = 1 AND payment.status = 1";
                    //echo $query;
                    $db->setQuery($query);
                    $jobs = $db->loadObjectList();
                    $unlimited = 0;
                    $canview = 0;
                    $resumesearch = 0;

                    foreach($jobs AS $job){
                            if($unlimited == 0){
                                    if ($job->viewresumeindetails != -1){
                                            $viewresumeindetails = "";
                                            $viewresumeindetails = $viewresumeindetails + $job->viewresumeindetails;
                                            $resumesearch = $resumesearch + $job->resumesearch;
                                    }else $unlimited = 1;
                            }
                    }
                    if ($unlimited == 0){
                        if ($viewresumeindetails == 0) $canview = 0; //can not add new job
                            if($jobid != ''){
                                $query = "SELECT SUM(apply.resumeview) AS totalview
                                FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply
                                WHERE apply.jobid = ".$jobid;
                                $db->setQuery($query);
                                $totalview = $db->loadResult();
                                if ($viewresumeindetails >= $totalview) $canview = 0; //can not add new job
                                else $canview = 1;
                                if ($myresume == 3) $canview = 1; // search resume
                            }else{
                                if($resumesearch > 0)$canview = 1; else $canview = 0;
                            }

                    }elseif ($unlimited == 1) $canview = 1; // unlimited
                }
                if ($canview == 0){ // check already view this resume
                            if($jobid != ''){
                                $query = "SELECT resumeview
                                FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply
                                WHERE apply.jobid = ".$jobid ." AND cvid = ".$id;

                                $db->setQuery($query);
                                $apply = $db->loadObject();
                                if ($apply->resumeview == 1) $canview = 1; //already view this resume
                                else $canview = 0;
                            }else $canview = 0;

                }
                if ($canview == 1){
						
                        if (is_numeric($id) == false) return false;
						if($this->validateViews() == 1){
							//  echo '<br> View';
							$query="SELECT * FROM view_resumes WHERE id = ".$id;	
							//echo $query;
							$db->setQuery($query);
							$resume = $db->loadObject();
							$result[0] = $resume;
							$result[1] = $resume;
							$result[2] = $resume;
						
						}else{
							//echo '<br> Table';

							$query = "SELECT app.* , cat.cat_title AS categorytitle, salary.rangestart, salary.rangeend, jobtype.title AS jobtypetitle
                                        ,heighesteducation.title AS heighesteducationtitle
                                        , nationality_country.name AS nationalitycountry
                                        , address_city.name AS address_city2 , address_county.name AS address_county2 , address_state.name AS address_state2 , address_country.name AS address_country
                                        , address1_city.name AS address1_city2 , address1_county.name AS address1_county2 , address1_state.name AS address1_state2 , address1_country.name AS address1_country
                                        , address2_city.name AS address2_city2 , address2_county.name AS address2_county2 , address2_state.name AS address2_state2 , address2_country.name AS address2_country
										, currency.symbol 


                                        FROM ".$db->nameQuote('#__wrecruit_resume')." AS app
                                        JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON app.job_category = cat.id
                                        JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON app.jobtype = jobtype.id
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS heighesteducation ON app.heighestfinisheducation = heighesteducation.id
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS nationality_country ON app.nationality = nationality_country.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON app.jobsalaryrange = salary.id
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS address_city ON app.address_city = address_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS address_county ON app.address_county = address_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS address_state ON app.address_state = address_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS address_country ON app.address_country = address_country.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS address1_city ON app.address1_city = address1_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS address1_county ON app.address1_county = address1_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS address1_state ON app.address1_state = address1_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS address1_country ON app.address1_country = address1_country.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS address2_city ON app.address2_city = address2_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS address2_county ON app.address2_county = address2_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS address2_state ON app.address2_state = address2_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS address2_country ON app.address2_country = address2_country.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = app.currencyid

                                        WHERE app.id = ". $id ;
							//echo '<br> sql '.$query;
							$query2 = "SELECT app.id

                                        , institute_city.name AS institute_city2 , institute_county.name AS institute_county2 , institute_state.name AS institute_state2 , institute_country.name AS institute_country
                                        , institute1_city.name AS institute1_city2 , institute1_county.name AS institute1_county2 , institute1_state.name AS institute1_state2 , institute1_country.name AS institute1_country
                                        , institute2_city.name AS institute2_city2 , institute2_county.name AS institute2_county2 , institute2_state.name AS institute2_state2 , institute2_country.name AS institute2_country
                                        , institute3_city.name AS institute3_city2 , institute3_county.name AS institute3_county2 , institute3_state.name AS institute3_state2 , institute3_country.name AS institute3_country

                                        , employer_city.name AS employer_city2 , employer_county.name AS employer_county2 , employer_state.name AS employer_state2 , employer_country.name AS employer_country
                                        , employer1_city.name AS employer1_city2 , employer1_county.name AS employer1_county2 , employer1_state.name AS employer1_state2 , employer1_country.name AS employer1_country
                                        , employer2_city.name AS employer2_city2 , employer2_county.name AS employer2_county2 , employer2_state.name AS employer2_state2 , employer2_country.name AS employer2_country
                                        , employer3_city.name AS employer3_city2 , employer3_county.name AS employer3_county2 , employer3_state.name AS employer3_state2 , employer3_country.name AS employer3_country

                                        FROM ".$db->nameQuote('#__wrecruit_resume')." AS app

                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS institute_city ON app.institute_city = institute_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS institute_county ON app.institute_county = institute_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS institute_state ON app.institute_state = institute_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS institute_country ON app.institute_country = institute_country.code

                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS institute1_city ON app.institute1_city = institute1_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS institute1_county ON app.institute1_county = institute1_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS institute1_state ON app.institute1_state = institute1_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS institute1_country ON app.institute1_country = institute1_country.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS institute2_city ON app.institute2_city = institute2_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS institute2_county ON app.institute2_county = institute2_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS institute2_state ON app.institute2_state = institute2_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS institute2_country ON app.institute2_country = institute2_country.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS institute3_city ON app.institute3_city = institute3_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS institute3_county ON app.institute3_county = institute3_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS institute3_state ON app.institute3_state = institute3_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS institute3_country ON app.institute3_country = institute3_country.code


                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS employer_city ON app.employer_city = employer_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS employer_county ON app.employer_county = employer_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS employer_state ON app.employer_state = employer_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS employer_country ON app.employer_country = employer_country.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS employer1_city ON app.employer1_city = employer1_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS employer1_county ON app.employer1_county = employer1_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS employer1_state ON app.employer1_state = employer1_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS employer1_country ON app.employer1_country = employer1_country.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS employer2_city ON app.employer2_city = employer2_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS employer2_county ON app.employer2_county = employer2_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS employer2_state ON app.employer2_state = employer2_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS employer2_country ON app.employer2_country = employer2_country.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS employer3_city ON app.employer3_city = employer3_city.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS employer3_county ON app.employer3_county = employer3_county.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS employer3_state ON app.employer3_state = employer3_state.code
                                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS employer3_country ON app.employer3_country = employer3_country.code

                                        WHERE app.id = ". $id ;

							$db->setQuery( 'SET SQL_BIG_SELECTS=1');
							$db->query();

							$db->setQuery($query);
							$resume = $db->loadObject();

							$db->setQuery($query2);
							$resume2 = $db->loadObject();
							$result[0] = $resume;
							$result[1] = $resume2;
							$result[2] = $this->getResumeViewbyId3($id);
						}	

						$query = "UPDATE ".$db->nameQuote('#__wrecruit_jobapply')." SET resumeview = 1 WHERE jobid = ".$jobid." AND cvid = ".$id;
						$db->setQuery( $query );
						$db->query();

                        $query = "UPDATE ".$db->nameQuote('#__wrecruit_resume')." SET hits = hits + 1 WHERE id = ".$id;
                        //echo '<br>sql '.$query;
                        $db->setQuery( $query );
                        if (!$db->query()) {
						
                                //return false;
                        }

                        $result[3] = $this->getFieldsOrdering(3); // resume fields
                        $result[4] = 1; // can view
                }else{
                       $result[4] = 0; // can not view
              }
		return $result;
		
	}

	function &getResumeViewbyId3($id) 
	{
		if (is_numeric($id) == false) return false;
		$db = &$this->getDBO();
		$query = "SELECT app.id
				, reference_city.name AS reference_city2 , reference_county.name AS reference_county2 , reference_state.name AS reference_state2 , reference_country.name AS reference_country 
				, reference1_city.name AS reference1_city2 , reference1_county.name AS reference1_county2 , reference1_state.name AS reference1_state2 , reference1_country.name AS reference1_country 
				, reference2_city.name AS reference2_city2 , reference2_county.name AS reference2_county2 , reference2_state.name AS reference2_state2 , reference2_country.name AS reference2_country 
				, reference3_city.name AS reference3_city2 , reference3_county.name AS reference3_county2 , reference3_state.name AS reference3_state2 , reference3_country.name AS reference3_country 

				FROM ".$db->nameQuote('#__wrecruit_resume')." AS app 
				
				

				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS reference_city ON app.reference_city = reference_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS reference_county ON app.reference_county = reference_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS reference_state ON app.reference_state = reference_state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS reference_country ON app.reference_country = reference_country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS reference1_city ON app.reference1_city = reference1_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS reference1_county ON app.reference1_county = reference1_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS reference1_state ON app.reference1_state = reference1_state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS reference1_country ON app.reference1_country = reference1_country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS reference2_city ON app.reference2_city = reference2_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS reference2_county ON app.reference2_county = reference2_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS reference2_state ON app.reference2_state = reference2_state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS reference2_country ON app.reference2_country = reference2_country.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS reference3_city ON app.reference3_city = reference3_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS reference3_county ON app.reference3_county = reference3_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS reference3_state ON app.reference3_state = reference3_state.code 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS reference3_country ON app.reference3_country = reference3_country.code 

				WHERE app.id = ". $id ;
		//echo '<br> sql '.$query;
		$db->setQuery($query);
		$resume = $db->loadObject();
		return $resume;
	}

	function storeCoverLetter()
	{
		global $resumedata;
		$row = &$this->getTable('coverletter');
		$data = JRequest :: get('post');


		if (!$row->bind($data)){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}

	function storeFilter()
	{
		global $resumedata;
		$user	=& JFactory::getUser();
		$row = &$this->getTable('filter');
		$data = JRequest :: get('post');

		$data['uid'] = $user->id;
		$data['status'] = 1;
		if (!$row->bind($data)){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if ($data['txtfilter_country'] == 'Country') $data['txtfilter_country'] = '';
		if ($data['txtfilter_state'] == 'State') $data['txtfilter_state'] = '';
		if ($data['txtfilter_county'] == 'County') $data['txtfilter_county'] = '';
		if ($data['txtfilter_city'] == 'City') $data['txtfilter_city'] = '';

                if ($data['cmbfilter_country'] != '') { $row->country = $data['cmbfilter_country']; $row->country_istext = 0;}
		elseif ($data['txtfilter_country'] != '') { $row->country = $data['txtfilter_country']; $row->country_istext = 1;}
		if ($data['cmbfilter_state'] != '') { $row->state = $data['cmbfilter_state']; $row->state_istext = 0;}
		elseif ($data['txtfilter_state'] != '') { $row->state = $data['txtfilter_state']; $row->state_istext = 1;}
		if ($data['cmbfilter_county'] != '') { $row->county = $data['cmbfilter_county']; $row->county_istext = 0;}
		elseif ($data['txtfilter_county'] != '') { $row->county = $data['txtfilter_county']; $row->county_istext = 1;}
		if ($data['cmbfilter_city'] != '') { $row->city = $data['cmbfilter_city']; $row->city_istext = 0;}
		elseif ($data['txtfilter_city'] != '') { $row->city = $data['txtfilter_city']; $row->city_istext = 1;}

		//echo 'cat '. $data['filter_jobcategory'];
		$row->category = $data['filter_jobcategory'];
		$row->jobtype = $data['filter_jobtype'];
		$row->salaryrange = $data['filter_jobsalaryrange'];
		$row->heighesteducation = $data['filter_heighesteducation'];

		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}

	function storeJobSearch($data)
	{
		global $resumedata;
		$row = &$this->getTable('jobsearch');
		
		if (!$row->bind($data)){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		$returnvalue = $this->canAddNewJobSearch($data['uid']);
		if ($returnvalue == 0) return 3; //not allowed save new search
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}

	function storeResumeSearch($data)
	{
		global $resumedata;
		$row = &$this->getTable('resumesearch');
		//$data = JRequest :: get('post');
		
		$data['date_start'] =  date('Y-m-d H:i:s',strtotime($data['date_start']));
		
		if (!$row->bind($data)){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		$returnvalue = $this->canAddNewResumeSearch($data['uid']);
		
		if ($returnvalue == 0) return 3; //not allowed save new search
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}

	function canAddNewJobSearch($uid) 
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$db = &$this->getDBO();
		$query = "SELECT COUNT(search.id) AS totalsearches, role.savesearchjob
		FROM ".$db->nameQuote('#__wrecruit_roles')." AS role
		JOIN ".$db->nameQuote('#__wrecruit_userroles')." AS userrole ON userrole.role = role.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_jobsearches')." AS search ON userrole.uid = search.uid 
		WHERE userrole.uid = ".$uid." GROUP BY role.savesearchjob";
		//echo $query;
		$db->setQuery($query);
		$job = $db->loadObject();
		if ($job){
			if ($job->savesearchjob == -1) return 1;
			else{
					if ($job->totalsearch < $job->savesearchjob ) return 1;
					else return 0;
				}
		}
		return 0;
	}

	function canAddNewResumeSearch($uid) 
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$db = &$this->getDBO();
		$query = "SELECT COUNT(search.id) AS totalsearches, role.savesearchresume
		FROM ".$db->nameQuote('#__wrecruit_roles')." AS role
		JOIN ".$db->nameQuote('#__wrecruit_userroles')." AS userrole ON userrole.role = role.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_resumesearches')." AS search ON userrole.uid = search.uid 
		WHERE userrole.uid = ".$uid." GROUP BY role.savesearchresume ";
		//echo $query;
		$db->setQuery($query);
		$resume = $db->loadObject();
		if ($resume){
			if ($resume->savesearchresume == -1) return 1;
			else{
					if ($resume->totalsearch < $resume->savesearchresume ) return 1;
					else return 0;
				}
		}
		return 0;
	}

	function deleteUserFilter()
	{
		$row = &$this->getTable('filter');
		$data = JRequest :: get('post');
		
		if (!$row->delete($data['id']))
		{
			$this->setError($row->getErrorMsg());
			return false;
		}

		return true;
	}
	
	function deleteJobSearch($searchid, $uid)
	{
		$db = &$this->getDBO();
		$row = &$this->getTable('jobsearch');

		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($searchid) == false) return false;

		$query = "SELECT COUNT(search.id) FROM ".$db->nameQuote('#__wrecruit_jobsearches')." AS search  
					WHERE search.id = ".$searchid." AND search.uid = ".$uid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$searchtotal = $db->loadResult();
		
		if ($searchtotal > 0){ // this search is same user
		
			if (!$row->delete($searchid))
			{
				$this->setError($row->getErrorMsg());
				return false;
			}
		}else return 2;	

		return true;
	}
	
	function deleteResumeSearch($searchid, $uid)
	{
		
		$db = &$this->getDBO();
		$row = &$this->getTable('resumesearch');
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($searchid) == false) return false;

		$query = "SELECT COUNT(search.id) FROM ".$db->nameQuote('#__wrecruit_resumesearches')." AS search  
					WHERE search.id = ".$searchid." AND search.uid = ".$uid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$searchtotal = $db->loadResult();
		
		if ($searchtotal > 0){ // this search is same user
		
			if (!$row->delete($searchid))
			{
				$this->setError($row->getErrorMsg());
				return false;
			}
		}else return 2;	

		return true;
	}
	
	function deleteCoverLetter($coverletterid, $uid)
	{
		$db = &$this->getDBO();
		$row = &$this->getTable('coverletter');
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($coverletterid) == false) return false;

		$query = "SELECT COUNT(letter.id) FROM ".$db->nameQuote('#__wrecruit_coverletters')." AS letter  
					WHERE letter.id = ".$coverletterid." AND letter.uid = ".$uid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
		
		if ($total > 0){ // this search is same user
		
			if (!$row->delete($coverletterid))
			{
				$this->setError($row->getErrorMsg());
				return false;
			}
		}else return 2;	

		return true;
	}

	
	function deleteResume($resumeid, $uid)
	{
		$row = &$this->getTable('resume');
		$data = JRequest :: get('post');
		
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($resumeid) == false) return false;
		$returnvalue = $this->resumeCanDelete($resumeid, $uid);
		if( $returnvalue == 1){
			if (!$row->delete($resumeid))	{
				$this->setError($row->getErrorMsg());
				return false;
			}
		}else return $returnvalue;	

		return true;
	}

	function deleteJob($jobid, $uid)
	{
		$row = &$this->getTable('job');
		$data = JRequest :: get('post');
		
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		$returnvalue = $this->jobCanDelete($jobid, $uid);
		if( $returnvalue == 1){
			if (!$row->delete($jobid))	{
				$this->setError($row->getErrorMsg());
				return false;
			}
		}else return $returnvalue;	

		return true;
	}

	function jobCanDelete($jobid, $uid){
		if (is_numeric($uid) == false) return false;
		$db = &$this->getDBO();
		if($jobid) if (is_numeric($jobid) == false) return false;

		$query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job  
					WHERE job.id = ".$jobid." AND job.uid = ".$uid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$jobtotal = $db->loadResult();
		
		if ($jobtotal > 0){ // this job is same user

			$query = "SELECT COUNT(apply.id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  
						WHERE apply.jobid = ".$jobid;
			
		$query = "SELECT 
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." WHERE jobid = ". $jobid .") 
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_featuredjobs')." WHERE jobid = ". $jobid .") 
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_goldjobs')." WHERE jobid = ". $jobid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_shortlistcandidates')." WHERE jobid = ". $jobid .")
					AS total ";
			//echo '<br> SQL '.$query;
			$db->setQuery($query);
			$total = $db->loadResult();
				
				if ($total > 0)
					return 2;
				else
					return 1;
		}else return 3; // 	this job is not of this user		
		
		
	}

	function jobEnforceDelete($jobid, $uid){ // this function may not use
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job  
					WHERE job.id = ".$jobid." AND job.uid = ".$uid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$jobtotal = $db->loadResult();
		
		if ($jobtotal > 0){ // this job is same user

			$query = "DELETE FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  
					  WHERE apply.jobid = ".$jobid;
			//echo '<br> SQL '.$query;
			$db->setQuery($query);
			if (!$db->query()) {
                 return 2; //error while delete job
            }
			return 1;
		}else return 3; // 	this job is not of this user		
	}

	function resumeCanDelete($resumeid, $uid){
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$db = &$this->getDBO();

		$query = "SELECT COUNT(resume.id) FROM ".$db->nameQuote('#__wrecruit_resume')." AS resume  
					WHERE resume.id = ".$resumeid." AND resume.uid = ".$uid;
		$db->setQuery($query);
		$resumetotal = $db->loadResult();
		
		if ($resumetotal > 0){ // this resume is same user
			$query = "SELECT 
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." WHERE cvid = ". $resumeid .") 
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_shortlistcandidates')." WHERE cvid = ". $resumeid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_featuredresumes')." WHERE resumeid = ". $resumeid .") 
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_goldresumes')." WHERE resumeid = ". $resumeid .")
					AS total ";
			//echo '<br> SQL '.$query;
			$db->setQuery($query);
			$total = $db->loadResult();
				
                        if ($total > 0)
                                return 2;
                        else
                                return 1;
		}else return 3; // 	this resume is not of this user		
	}

	
	function storeResume($jobid)
	{
		global $resumedata;
		if($jobid) if ((is_numeric($jobid) == false) || ($jobid == 0) || ($jobid == '')) return false;
		$row = &$this->getTable('resume');
		$resumedata = JRequest :: get('post');
	//	if ( !$resumedata['id'] ){
			if ( !$this->_config )
				$this->getConfig('');
			foreach ($this->_config as $conf){
				if ($conf->configname == 'empautoapprove')
					if ( !$resumedata['id'] ) $resumedata['status'] = $conf->configvalue;
				if ($conf->configname == 'resume_photofilesize')
					$photofilesize = $conf->configvalue;
				if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
			}
	//	}

		if($dateformat == 'm-d-Y'){
			$arr = explode('-', $resumedata['date_start']);
			$resumedata['date_start'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
		}elseif($dateformat == 'd-m-Y'){
			$arr = explode('-', $resumedata['date_start']);
			$resumedata['date_start'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
		}
	 
		$resumedata['date_start'] =  date('Y-m-d H:i:s',strtotime($resumedata['date_start']));	
		$resumedata['resume'] = JRequest::getVar('resume', '', 'post', 'string', JREQUEST_ALLOWRAW);
		if($_FILES['photo']['size'] > 0){
			$uploadfilesize = $_FILES['photo']['size'];
			$uploadfilesize = $uploadfilesize / 1024; //kb
			if($uploadfilesize > $photofilesize){ // logo
				return 7; // file size error	
			}	
		}		

		if($_FILES['resumefile']['size'] > 0){
			$file_name = $_FILES['resumefile']['name']; // file name
			$resumedata['filename'] = $file_name;
			$resumedata['filecontent'] = '';
		}else {
			if ($resumedata['deleteresumefile'] == 1){
				$resumedata['filename'] = '';
				$resumedata['filecontent'] = '';
			}
		}		
		if($_FILES['photo']['size'] > 0){
			$file_name = $_FILES['photo']['name']; // file name
			$resumedata['photo'] = $file_name;
		}else {
			if ($resumedata['deletephoto'] == 1){
				$resumedata['photo'] = '';
			}	
		}
//		if ($returnvalue != 1)
//			return $returnvalue;

		if (!$row->bind($resumedata))
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		if (!$row->check())
		{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}

		if (!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		$resumereturnvalue = $this->uploadResume($row->id); 
		if($resumereturnvalue != 1){
			$resumedeletedata['id'] = $row->id;		
			$resumedeletedata['filename'] = '';
			$row->bind($resumedeletedata);
			$row->store();
		}
		$returnvalue = $this->uploadPhoto($row->id);
		if($resumereturnvalue != 1){
			$resumedeletedata['id'] = $row->id;		
			$resumedeletedata['photo'] = '';
			$row->bind($resumedeletedata);
			$row->store();
		}
		if($jobid)$returnvalue = $this->visitorJobApply($jobid,$row->id);
		if($resumedata['id'] == '') $this->sendMailtoAdmin($row_id,$data['uid'],3);//only for new

		return $resumereturnvalue;
	}

	function uploadResume($id)
	{

                if (is_numeric($id) == false) return false;
		global $resumedata ;
		$db =& JFactory::getDBO();
		//$resumequery = "SELECT * FROM ".$db->nameQuote('#__wrecruit_resume') ."
		//WHERE uid = ".$db->Quote($u_id);
		//echo '<br>sql '.$resumequery;
		$iddir = 'resume_'.$id;
                if(! isset($this->_config)) $this->getConfig('');
                foreach ($this->_config as $conf){
                        if ($conf->configname == 'data_directory') $datadirectory = $conf->configvalue;
                }
		if($_FILES['resumefile']['size'] > 0){
			$file_name = $_FILES['resumefile']['name']; // file name
			$file_tmp = $_FILES['resumefile']['tmp_name']; // actual location
			$file_size = $_FILES['resumefile']['size']; // file size
			$file_type = $_FILES['resumefile']['type']; // mime type of file determined by php
			$file_error = $_FILES['resumefile']['error']; // any error!. get reason here

			if( !empty($file_tmp)){	// only MS office and text file is accepted.
				$ext = $this->getExtension($file_name);
				if (($ext != "txt") && ($ext != "doc") && ($ext != "docx") && ($ext != "pdf") && ($ext != "opt") && ($ext != "rtf"))
					return 6; //file type mistmathc
/*
				if( !(($file_type=="application/msword") || ($file_type=="text/plain")) )
				{
					return 6; //file type mistmathc
				}
*/			}

                        $path =JPATH_BASE.'/'.$datadirectory;
			//$path =JPATH_BASE.'/components/com_wrecruit';
			if (!file_exists($path)){ // creating resume directory
				mkdir($path, 0755);
			}
			$path= $path . '/data';
			if (!file_exists($userpath)){ // create user directory
				mkdir($path, 0755);
			}
			$path= $path . '/jobseeker';
			if (!file_exists($path)){ // create user directory
				mkdir($path, 0755);
			}
			$userpath= $path . '/'.$iddir;
			if (!file_exists($userpath)){ // create user directory
				mkdir($userpath, 0755);
			}
			$userpath= $path . '/'.$iddir.'/resume';
			if (!file_exists($userpath)){ // create user directory
				mkdir($userpath, 0755);
			}
			$files = glob($userpath.'/*.*');
			array_map('unlink', $files);  //delete all file in user directory
			
			move_uploaded_file($file_tmp, $userpath.'/' . $file_name);
			//unlink($file_tmp);
			
//			$resumedata['filename'] = $file_name;
//			$resumedata['filecontent'] = '';
			return 1;
		}else {
			if ($resumedata['deleteresumefile'] == 1){
                                $path =JPATH_BASE.'/'.$datadirectory.'/data/jobseeker';
				//$path =JPATH_BASE.'/components/com_wrecruit/data/jobseeker';
				$userpath= $path . '/'.$iddir.'/resume';
				$files = glob($userpath.'/*.*');
				array_map('unlink', $files);
				$resumedata['filename'] = '';
				$resumedata['filecontent'] = '';
			}else{
//				$db->setQuery( $resumequery );
//				$resume = $db->loadObject();
//				if ( isset($resume) ){ // if already file upload then pick the path
//						$resumedata['filename'] = $resume->filename;
//						$resumedata['filecontent'] = '';
//				}
			}
			return 1;
		}

	}


	function uploadPhoto($id)
	{
		if (is_numeric($id) == false) return false;
		global $resumedata ;
		$db =& JFactory::getDBO();
		$resumequery = "SELECT * FROM ".$db->nameQuote('#__wrecruit_resume') ."
		WHERE uid = ".$db->Quote($u_id);
		//echo '<br>sql '.$resumequery;
		$iddir = 'resume_'.$id;
                if(! isset($this->_config)) $this->getConfig('');
                foreach ($this->_config as $conf){
                        if ($conf->configname == 'data_directory') $datadirectory = $conf->configvalue;
                }
		if($_FILES['photo']['size'] > 0){
			$file_name = $_FILES['photo']['name']; // file name
			$file_tmp = $_FILES['photo']['tmp_name']; // actual location
			$file_size = $_FILES['photo']['size']; // file size
			$file_type = $_FILES['photo']['type']; // mime type of file determined by php
			$file_error = $_FILES['photo']['error']; // any error!. get reason here

			if( !empty($file_tmp)){	
				$ext = $this->getExtension($file_name);
				if (($ext != "gif") && ($ext != "jpg") && ($ext != "jpeg") && ($ext != "png"))
					return 6; //file type mistmathc
			}

                        $path =JPATH_BASE.'/'.$datadirectory;
			//$path =JPATH_BASE.'/components/com_wrecruit';
			if (!file_exists($path)){ // creating resume directory
				mkdir($path, 0755);
			}
			$path = $path.'/data';
			if (!file_exists($path)){ // creating resume directory
				mkdir($path, 0755);
			}
			$path = $path.'/jobseeker';
			if (!file_exists($path)){ // creating resume directory
				mkdir($path, 0755);
			}
			$userpath= $path . '/'.$iddir;
			if (!file_exists($userpath)){ // create user directory
				mkdir($userpath, 0755);
			}
			$userpath= $path . '/'.$iddir.'/photo';
			if (!file_exists($userpath)){ // create user directory
				mkdir($userpath, 0755);
			}
			$files = glob($userpath.'/*.*');
			array_map('unlink', $files);  //delete all file in user directory
			
			move_uploaded_file($file_tmp, $userpath.'/' . $file_name);
			//unlink($file_tmp);
			
//			$resumedata['photo'] = $file_name;
			return 1;
		}else {
			if ($resumedata['deletephoto'] == 1){
				//$path =JPATH_BASE.'/components/com_wrecruit/data/jobseeker';
                                $path =JPATH_BASE.'/'.$datadirectory.'/data/jobseeker';
				$userpath= $path . '/'.$iddir.'/photo';
				$files = glob($userpath.'/*.*');
				array_map('unlink', $files);
				$resumedata['photo'] = '';
			}else{
//				$db->setQuery( $resumequery );
//				$resume = $db->loadObject();
//				if ( isset($resume) ){ // if already file upload then pick the path
//						$resumedata['photo'] = $resume->filename;
//				}
			}
			return 1;
		}

	}


	function uploadFile($id, $action, $isdeletefile)
	{

                //echo '<br>upload file ';
		if (is_numeric($id) == false) return false;
		$db =& JFactory::getDBO();
		if(! isset($this->_config)) $this->getConfig('');
		foreach ($this->_config as $conf){
			if ($conf->configname == 'data_directory') $datadirectory = $conf->configvalue;
		}
                $path =JPATH_BASE.'/'.$datadirectory;
		if (!file_exists($path)){ // create user directory
			mkdir($path, 0755);
		}
                //$path =JPATH_BASE.'/components/com_wrecruit';
		$isupload = false;
		$path= $path . '/data';
		if (!file_exists($path)){ // create user directory
			mkdir($path, 0755);
		}
		$path= $path . '/employer';
		if (!file_exists($path)){ // create user directory
			mkdir($path, 0755);
		}
		if ($action == 1) { //Company logo
			if($_FILES['logo']['size'] > 0){
				$file_name = $_FILES['logo']['name']; // file name
				$file_tmp = $_FILES['logo']['tmp_name']; // actual location
				
				$ext = $this->getExtension($file_name);
				$ext = strtolower($ext);
				if (($ext != "gif") && ($ext != "jpg") && ($ext != "jpeg") && ($ext != "png"))
					return 6; //file type mistmathc
					
				$userpath= $path . '/comp_'.$id;
				if (!file_exists($userpath)){ // create user directory
					mkdir($userpath, 0755);
				}
				$userpath= $userpath. '/logo';
				if (!file_exists($userpath)){ // create logo directory
					mkdir($userpath, 0755);
				}
				$isupload = true;
			}
		}elseif ($action == 2) { //Company small logo
			if($_FILES['smalllogo']['size'] > 0){
				$file_name = $_FILES['smalllogo']['name']; // file name
				$file_tmp = $_FILES['smalllogo']['tmp_name']; // actual location
				
				$ext = $this->getExtension($file_name);
				$ext = strtolower($ext);
				if (($ext != "gif") && ($ext != "jpg") && ($ext != "jpeg") && ($ext != "png"))
					return 6; //file type mistmathc
					
				$userpath= $path . '/comp_'.$id;
				if (!file_exists($userpath)){ // create user directory
					mkdir($userpath, 0755);
				}
				$userpath= $userpath. '/smalllogo';
				if (!file_exists($userpath)){ // create logo directory
					mkdir($userpath, 0755);
				}
				$isupload = true;
			}
		}elseif ($action == 3) { //About Company
			if($_FILES['aboutcompany']['size'] > 0){
				$file_name = $_FILES['aboutcompany']['name']; // file name
				$file_tmp = $_FILES['aboutcompany']['tmp_name']; // actual location
				
				$ext = $this->getExtension($file_name);
				$ext = strtolower($ext);
				if (($ext != "txt") && ($ext != "doc") && ($ext != "docx") && ($ext != "pdf") && ($ext != "opt") && ($ext != "rtf"))
					return 6; //file type mistmathc
					
				$userpath= $path . '/comp_'.$id;
				if (!file_exists($userpath)){ // create user directory
					mkdir($userpath, 0755);
				}
				$userpath= $userpath. '/aboutcompany';
				if (!file_exists($userpath)){ // create logo directory
					mkdir($userpath, 0755);
				}
				$isupload = true;
			}
	
		
		}
		
		if ($isupload){
			$files = glob($userpath.'/*.*');
			array_map('unlink', $files);  //delete all file in directory
			
			move_uploaded_file($file_tmp, $userpath.'/' . $file_name);
			//unlink($file_tmp);
			
			return 1;
		}else { // DELETE FILES
			if ($action == 1) { // company logo
				if ($isdeletefile == 1){
					$userpath= $path . '/comp_'.$id . '/logo';
					$files = glob($userpath.'/*.*');
					array_map('unlink', $files); // delete all file in the direcoty 
				}
			}elseif ($action == 2) { // company small logo
				if ($isdeletefile == 1){
					$userpath= $path . '/comp_'.$id . '/smalllogo';
					$files = glob($userpath.'/*.*');
					array_map('unlink', $files); // delete all file in the direcoty 
				}
			}elseif ($action == 3) { // about company 
				if ($isdeletefile == 1){
					$userpath= $path . '/comp_'.$id . '/aboutcompany';
					$files = glob($userpath.'/*.*');
					array_map('unlink', $files); // delete all file in the direcoty 
				}
			}
			return 1;
		}

	}

	function &listAddressData($data,$val)
	{
		$db = &$this->getDBO();
		
		if ($data=='country') {  // country
			$query  = "SELECT code, name FROM ".$db->nameQuote('#__wrecruit_countries')."  WHERE enabled = 'Y' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='country' size='40' maxlength='100'  />";
			}else {
				$return_value = "<select name='country' class='inputbox' onChange=\"dochange('state', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_COUNTRY') ."</option>\n";

				foreach($result as $row){
			       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}

		}else if ($data=='state') {  // states
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_states')."  WHERE enabled = 'Y' AND countrycode= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='state' size='40' maxlength='100'  />";
			}else {
				$return_value = "<select name='state' class='inputbox' onChange=\"dochange('county', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_STATE') ."</option>\n";

				foreach($result as $row){
					   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}
		}else if ($data=='county') {  // county
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_counties')."  WHERE enabled = 'Y' AND statecode= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))
			{
				$return_value = "<input class='inputbox' type='text' name='county' size='40' maxlength='100'  />";
			}else
			{
				  $return_value = "<select name='county' class='inputbox' onChange=\"dochange('city', this.value)\">\n";
				  $return_value .= "<option value='0'>". JText::_('JS_CHOOSE_COUNTY') ."</option>\n";
				  
				  
				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}


		} else if ($data=='city') { // city
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_cities')."  WHERE enabled = 'Y' AND countycode= ".$db->quote($val)." ORDER BY 'name'";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			//if (mysql_num_rows($result)== 0)
			if (empty($result))
			{
				$return_value = "<input class='inputbox' type='text' name='city' size='40' maxlength='100'  />";
			}else
			{
				  $return_value = "<select name='city' class='inputbox' onChange=\"dochange('zipcode', this.value)\">\n";
				  $return_value .= "<option value='0'>". JText::_('JS_CHOOSE_CITY') ."</option>\n";
				  
				  
				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}

		}
		return $return_value;
	}

	function &listSearchAddressData($data,$val)
	{
		$db = &$this->getDBO();

		if ($data=='country') {  // country
                        if($val == -1) $query  = "SELECT code, name FROM ".$db->nameQuote('#__wrecruit_countries')." WHERE enabled = 'Y' ORDER BY name ASC";
                        else $query  = "SELECT code, name FROM ".$db->nameQuote('#__wrecruit_countries')." WHERE enabled = 'Y' AND code= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='country' size='40' maxlength='100'  />";
			}else {
				$return_value = "<select name='country' class='inputbox' onChange=\"dochange('state', this.value)\">\n";
				$return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";

				foreach($result as $row){
			       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}

		}else if ($data=='state') {  // states
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_states')."  WHERE enabled = 'Y' AND countrycode= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='state' size='40' maxlength='100'  />";
			}else {
				$return_value = "<select name='state' class='inputbox' onChange=\"dochange('county', this.value)\">\n";
				$return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";

				foreach($result as $row){
					   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}
		}else if ($data=='county') {  // county
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_counties')."  WHERE enabled = 'Y' AND statecode= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='county' size='40' maxlength='100'  />";
			}else
			{
				  $return_value = "<select name='county' class='inputbox' onChange=\"dochange('city', this.value)\">\n";
				  $return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";
				  
				  
				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}


		} else if ($data=='city') { // city
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_cities')."  WHERE enabled = 'Y' AND countycode= ".$db->quote($val)." ORDER BY 'name'";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			//if (mysql_num_rows($result)== 0)
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='city' size='40' maxlength='100'  />";
			}else
			{
				  $return_value = "<select name='city' class='inputbox' onChange=\"dochange('zipcode', this.value)\">\n";
				  $return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";
				  
				  
				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}

		}
		return $return_value;
	}

	function &listModuleSearchAddressData($data,$val,$for)
	{
		$db = &$this->getDBO();
		$methodname = $for.'dochange';
		
		if ($data=='country') {  // country
			$query  = "SELECT code, name FROM ".$db->nameQuote('#__wrecruit_countries')." WHERE enabled = 'Y' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='country' size='27' maxlength='100'  />";
			}else {
				$return_value = "<select name='country' class='inputbox' style='width:160px;' onChange=\"$methodname('state', this.value)\">\n";
				$return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";

				foreach($result as $row){
			       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}

		}else if ($data=='state') {  // states
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_states')."  WHERE enabled = 'Y' AND countrycode= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='state' size='27' maxlength='100'  />";
			}else {
				$return_value = "<select name='state' class='inputbox' style='width:160px;' onChange=\"$methodname('county', this.value)\">\n";
				$return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";

				foreach($result as $row){
					   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}
		}else if ($data=='county') {  // county
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_counties')."  WHERE enabled = 'Y' AND statecode= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='county' size='27' maxlength='100'  />";
			}else
			{
				  $return_value = "<select name='county' class='inputbox' style='width:160px;' onChange=\"$methodname('city', this.value)\">\n";
				  $return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";
				  
				  
				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}


		} else if ($data=='city') { // city
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_cities')."  WHERE enabled = 'Y' AND countycode= ".$db->quote($val)." ORDER BY 'name'";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			//if (mysql_num_rows($result)== 0)
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='city' size='27' maxlength='100'  />";
			}else
			{
				  $return_value = "<select name='city' class='inputbox' style='width:160px;' onChange=\"$methodname('zipcode', this.value)\">\n";
				  $return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";
				  
				  
				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}

		}
		return $return_value;
	}

	function &listFilterAddressData($data,$val)
	{
		$db = &$this->getDBO();

		if(! isset($this->_config)){
			$this->getConfig('');
		}	
		foreach ($this->_config as $conf){
			if ($conf->configname == 'filter_address_fields_width')
				$address_fields_width = $conf->configvalue;
		}

		if ($data=='country') {  // country
			$query  = "SELECT code, name FROM ".$db->nameQuote('#__wrecruit_countries')." WHERE enabled = 'Y' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' style='width:".$address_fields_width."px;color:#808080;' type='text' name='txtfilter_country' size='25' maxlength='50' value='Country' />";
			}else {
				$return_value = "<select name='cmbfilter_country' style='width:".$address_fields_width."px;' onChange=\"filter_dochange('filter_state', this.value)\">\n";
				$return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";
				foreach($result as $row){
			       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}

		}else if ($data=='filter_state') {  // states
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_states')."  WHERE enabled = 'Y' AND countrycode= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' style='width:".$address_fields_width."px;color:#808080;' name='txtfilter_state' size='25' maxlength='50' value='State' onfocus='if(this.value == \"State\"){this.value = \"\";this.style.color=\"black\";};' onblur='if(this.value == \"\") { this.style.color=\"#808080\";this.value=\"State\";  }' />";
			}else {
				$return_value = "<select name='cmbfilter_state' class='inputbox' style='width:".$address_fields_width."px;' onChange=\"filter_dochange('filter_county', this.value)\">\n";
				$return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";

				foreach($result as $row){
					   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}
		}else if ($data=='filter_county') {  // county
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_counties')."  WHERE enabled = 'Y' AND statecode= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' style='width:".$address_fields_width."px;color:#808080;' name='txtfilter_county' size='25' maxlength='50' value='County' onfocus='if(this.value == \"County\"){this.value = \"\";this.style.color=\"black\";};' onblur='if(this.value == \"\") { this.style.color=\"#808080\";this.value=\"County\";  }'/>";
			}else
			{
				  $return_value = "<select name='cmbfilter_county' class='inputbox' style='width:".$address_fields_width."px;' onChange=\"filter_dochange('filter_city', this.value)\">\n";
				  $return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";
				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}

		} else if ($data=='filter_city') { // city
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_cities')."  WHERE enabled = 'Y' AND countycode= ".$db->quote($val)." ORDER BY 'name'";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			//if (mysql_num_rows($result)== 0)
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' style='width:".$address_fields_width."px;color:#808080;' name='txtfilter_city' size='25' maxlength='50' value='City' onfocus='if(this.value == \"City\"){this.value = \"\";this.style.color=\"black\";};' onblur='if(this.value == \"\") { this.style.color=\"#808080\";this.value=\"City\";  }'/>";
			}else
			{
				$return_value = "<select name='cmbfilter_city' class='inputbox' style='width:".$address_fields_width."px;' onChange=\"filter_dochange('zipcode', this.value)\">\n";
				$return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";
				foreach($result as $row){
				   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}
		}
		return $return_value;
	}

	function &listEmpAddressData($name, $myname, $nextname, $data, $val)
	{
		$db = &$this->getDBO();

		
		if ($data=='country') {  // country
			$query  = "SELECT code, name FROM ".$db->nameQuote('#__wrecruit_countries')."  WHERE enabled = 'Y' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='$name' size='40' maxlength='100'  />";
			}else {

				$return_value = "<select name='$name' onChange=\"dochange(\"$myname\",'state', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_COUNTRY') ."</option>\n";

				foreach($result as $row){
				   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}

		}else if ($data=='state') {  // states
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_states')."  WHERE enabled = 'Y' AND countrycode= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);

			$result = $db->loadObjectList();
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='$name' size='40' maxlength='100'  />";
			}else
			{
				$return_value = "<select name='$name' class='inputbox' onChange=\"dochange('$myname','$nextname','','county', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_STATE') ."</option>\n";
				  
				foreach($result as $row){
					   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}
		}else if ($data=='county') {  // county
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_counties')."  WHERE enabled = 'Y' AND statecode= ".$db->quote($val)." ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='$name' size='40' maxlength='100'  />";
			}else
			{
				$return_value = "<select name='$name' class='inputbox' onChange=\"dochange('$myname','','','city', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_COUNTY') ."</option>\n";
				  
				foreach($result as $row){
					   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}


		} else if ($data=='city') { // second dropdown
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_cities')."  WHERE enabled = 'Y' AND countycode= ".$db->quote($val)." ORDER BY 'name'";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='$name' size='40' maxlength='100'  />";
			}else
			{
				$return_value = "<select name='$name' class='inputbox' onChange=\"dochange('zipcode', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_CITY') ."</option>\n";
				  
				foreach($result as $row){
				    $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}

		}
		return $return_value;
	}		

	function &listDepartments($val)
	{
		$db = &$this->getDBO();
		
		if (is_numeric($val) == false) return false;
		$query  = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_departments')."  WHERE status = 1 AND companyid = ".$val."
				ORDER BY name ASC";
		$db->setQuery($query);
		$result = $db->loadObjectList();

		if (isset($result)){	
			$return_value = "<select name='departmentid' class='inputbox' >\n";

			foreach($result as $row){
				$return_value .= "<option value=\"$row->id\" >$row->name</option> \n" ;
			}
			$return_value .= "</select>\n";
		}

		return $return_value;
	}
	function &listSubCategories($val)
	{
		$db = &$this->getDBO();

		$query  = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_subcategories')."  WHERE status = 1 AND categoryid = ".$val." ORDER BY title ASC";
		$db->setQuery($query);
		$result = $db->loadObjectList();

		if (isset($result)){
			$return_value = "<select name='subcategoryid' class='inputbox' >\n";
                                $return_value .= "<option value='' >".JText::_('JS_SUB_CATEGORY')."</option> \n" ;
			foreach($result as $row){
				$return_value .= "<option value=\"$row->id\" >$row->title</option> \n" ;
			}
			$return_value .= "</select>\n";
		}
		return $return_value;
	}

	function &getResumeDetail($uid, $jobid, $resumeid)
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($resumeid) == false) return false;

		$db = &$this->getDBO();
                $canview = 0;

                $query = "SELECT apply.resumeview FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply
                WHERE apply.jobid = ".$jobid . " AND apply.cvid = ".$resumeid;
                $db->setQuery($query);
                $alreadyview = $db->loadObject();

                if ($alreadyview->resumeview == 1) $canview = 1;//already view this resume
                if ($canview == 0){
                    $query = "SELECT package.viewresumeindetails, package.packageexpireindays, payment.created
                    FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
                    JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
                    WHERE payment.uid = ".$uid."
                    AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()";
                    //echo $query;
                    $db->setQuery($query);
                    $jobs = $db->loadObjectList();
                    $unlimited = 0;

                    foreach($jobs AS $job){
                            if($unlimited == 0){
                                    if ($job->viewresumeindetails != -1){
                                            $viewresumeindetails = $viewresumeindetails + $job->viewresumeindetails;
                                    }else $unlimited = 1;
                            }
                    }
                    if ($unlimited == 0){
                        if ($viewresumeindetails == 0) $canview = 0; //can not add new job
                            $query = "SELECT SUM(apply.resumeview) AS totalview
                            FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply
                            WHERE apply.jobid = ".$jobid;
                            //echo $query;
                            $db->setQuery($query);
                            $totalview = $db->loadResult();

                            if ($viewresumeindetails <= $totalview) $canview = 0; //can not add new job
                            else $canview = 1;

                    }elseif ($unlimited == 1) $canview = 1; // unlimited
                }

                if ($canview == 1){
                    $query = "UPDATE ".$db->nameQuote('#__wrecruit_jobapply')." SET resumeview = 1 WHERE jobid = ".$jobid." AND cvid = ".$resumeid;
                    $db->setQuery( $query );
                    $db->query();
                    
                    $query = "SELECT apply.apply_date, app.iamavailable
                                    , app.id AS appid, app.first_name, app.last_name, app.email_address ,app.address_county
                                    ,app.jobtype,app.gender,app.institute,app.institute_study_area ,app.address_state ,app.address_city
                                    ,app.total_experience, app.jobsalaryrange,country.name AS countryname,state.name AS statename
                                    ,county.name AS countyname,city.name AS cityname
                                    , salary.rangestart, salary.rangeend,education.title AS educationtitle
                                    FROM ".$db->nameQuote('#__wrecruit_resume')." AS app
                                    JOIN ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  ON apply.cvid = app.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS  education  ON app.heighestfinisheducation=education.id
                                    LEFT OUTER JOIN  ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary	ON	app.jobsalaryrange=salary.id
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON app.address_country  = country.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON app.address_state = state.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON app.address_county  = county.code
                                    LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON app.address_city = city.code

                    WHERE app.id = ".$resumeid;
                    //echo '<br> SQL '.$query;
                    $db->setQuery($query);
                    $resume = $db->loadObject();

                    if (isset($resume)){

                            $return_value = "<table cellpadding='0' cellspacing='0' border='1' width='100%'>\n";
                            $return_value .= "<tr><td>\n";
                            $return_value .= "<table cellpadding='0' cellspacing='0' border='0' width='100%'>\n";
                            $return_value .= "<tr class='odd'>\n";
                            $return_value .= "<td width='40%' ><b>".JText::_('JS_EDUCATION')."</b></td>\n";
                            $return_value .= "<td >".$resume->educationtitle." </td>\n";
                            $return_value .= "<td width='20'><input type='button' class='button' onclick='clsjobdetail(\"resumedetail_$resume->appid\")' value='X'> </td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "<tr class='even'>\n";
                            $return_value .= "<td ><b>".JText::_('JS_INSTITUTE')."</b></td>\n";
                            $return_value .= "<td >".$resume->institute." </td>\n";
                            $return_value .= "<td ></td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "<tr class='odd'>\n";
                            $return_value .= "<td ><b>".JText::_('JS_STUDY_AREA')."</b></td>\n";
                            $return_value .= "<td >".$resume->institute_study_area." </td>\n";
                            $return_value .= "<td ></td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "<tr class='even'>\n";
                            $return_value .= "<td ><b>".JText::_('JS_EXPERIENCE')."</b></td>\n";
                            $return_value .= "<td >".$resume->total_experience." </td>\n";
                            $return_value .= "<td ></td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "<tr class='odd'>\n";
                            $return_value .= "<td ><b>".JText::_('JS_I_AM_AVAILABLE')."</b></td>\n";
                            if($resume->iamavailable==1) $return_value .= "<td >Yes </td>\n";
                            else $return_value .= "<td >No </td>\n";
                            $return_value .= "<td ></td>\n";
                            $return_value .= "</tr>\n";

                            $return_value .= "<tr class='even'>\n";
                            $return_value .= "<td ><b>".JText::_('JS_CITY')."</b></td>\n";
                            if($resume->cityname) $return_value .= "<td >".$resume->cityname." </td>\n";
                            else $return_value .= "<td >".$resume->address_city." </td>\n";
                            $return_value .= "<td ></td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "<tr class='odd'>\n";
                            $return_value .= "<td ><b>".JText::_('JS_COUNTY')."</b></td>\n";
                            if($resume->countyname) $return_value .= "<td >".$resume->countyname." </td>\n";
                            else $return_value .= "<td >".$resume->address_county." </td>\n";
                            $return_value .= "<td ></td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "<tr class='even'>\n";
                            $return_value .= "<td ><b>".JText::_('JS_STATE')."</b></td>\n";
                            if($resume->statename) $return_value .= "<td >".$resume->statename." </td>\n";
                            else $return_value .= "<td >".$resume->address_state." </td>\n";
                            $return_value .= "<td ></td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "<tr class='odd'>\n";
                            $return_value .= "<td ><b>".JText::_('JS_COUNTRY')."</b></td>\n";
                            $return_value .= "<td >".$resume->countryname." </td>\n";
                            $return_value .= "<td ></td>\n";
                            $return_value .= "</tr>\n";

                            $return_value .= "<tr>\n";
                            $return_value .= "<td colspan='3' align='center'>\n";
                            $return_value .= "<input type='hidden' name='resumeid' value=".$resumeid." />\n";
                            $return_value .= "</td>\n";
                            $return_value .= "</tr>\n";

                            $return_value .= "</tr>\n";
                            $return_value .= "</table>\n";

                            $return_value .= "</td></tr>\n";
                            $return_value .= "</table>\n";
                    }
                }else{
                            $return_value = "<table cellpadding='0' cellspacing='0' border='1' width='100%'>\n";
                            $return_value .= "<tr><td>\n";
                            $return_value .= "<table cellpadding='0' cellspacing='0' border='0' width='100%'>\n";
                            $return_value .= "<tr class='odd'>\n";
                            $return_value .= "<td ><b>".JText::_('JS_YOU_CAN_NOT_VIEW_RESUME_DETAIL')."</b></td>\n";
                            $return_value .= "<td width='20'><input type='button' class='button' onclick='clsjobdetail(\"resumedetail_$resume->appid\")' value=".JText::_('JS_CLOSE')."> </td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "</table>\n";

                            $return_value .= "</td></tr>\n";
                            $return_value .= "</table>\n";


                }

		return $return_value;
	}

	function &getMyFoldersAJAX($uid, $jobid, $resumeid,$applyid)
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($resumeid) == false) return false;
                $option = 'com_wrecruit';
		$db = &$this->getDBO();
                $canview = 0;

                $canadd = $this->canResumeAddintoFolder($uid,$jobid);
                if ($canadd == 1){
                    $myfolders = $this->getMyFoldersForCombo($uid,'');
                    if($myfolders ) $folders = JHTML::_('select.genericList', $myfolders, 'folderid', 'class="inputbox required" '. '', 'value', 'text', '');
                    else $folders = JText::_('YOU_DO_NOT_HAVE_FOLDERS');

                    $return_value = "<table cellpadding='0' cellspacing='0' border='1' width='100%'>\n";
                            $return_value .= "<tr><td>\n";
                            $return_value .= "<table cellpadding='0' cellspacing='0' border='0' width='100%'>\n";
                            $return_value .= "<tr class='odd'>\n";
                            $return_value .= "<td width='30%' align='right' ><b>".JText::_('JS_FOLDER')."</b></td>\n";
                            $return_value .= "<td width='20%'>".$folders." </td>\n";
                            if($myfolders ){
                                $return_value .= "<td  align='left'><input type='button' class='button' onclick='saveaddtofolder(".$jobid.",".$resumeid.")' value='".JText::_('JS_ADD')."'> </td>\n";
                            }
                            $return_value .= "</tr>\n";
                            $return_value .= "</table>\n";
                            $return_value .= "</td></tr>\n";
                            $return_value .= "</table>\n";
                }else{  
                            $return_value = "<table cellpadding='0' cellspacing='0' border='1' width='100%'>\n";
                            $return_value .= "<tr><td>\n";
                            $return_value .= "<table cellpadding='0' cellspacing='0' border='0' width='100%'>\n";
                            $return_value .= "<tr class='odd'>\n";
                            $return_value .= "<td ><b>".JText::_('JS_YOU_DO_NOT_HAVE_RIGHT')."</b></td>\n";
                            $return_value .= "<td width='20'><input type='button' class='button' onclick='clsaddtofolder(\"resumeaction_$applyid\")' value=".JText::_('JS_CLOSE')."> </td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "</table>\n";

                            $return_value .= "</td></tr>\n";
                            $return_value .= "</table>\n";


                }

		return $return_value;
	}
        function canResumeAddintoFolder($uid,$jobid){
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;

		$db = &$this->getDBO();
                $canadd = 0;
                $query = "SELECT package.folders, package.packageexpireindays, payment.created
                FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
                JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
                JOIN ".$db->nameQuote('#__wrecruit_jobs')." AS job ON job.packageid = package.id
                WHERE payment.uid = ".$uid." AND job.id = ".$jobid;
                //echo $query;
                $db->setQuery($query);
                $package = $db->loadObject();

                if ($package->folders > 0) return 1; else return 0;
        }

        function &getEmpOptions()
	{
		if ( !$this->_empoptions )
		{
			$this->_empoptions = array();

		$gender = array(
			'0' => array('value' => 1,'text' => JText::_('JS_MALE')),
			'1' => array('value' => 2,'text' => JText::_('JS_FEMALE')),);

			$job_type = $this->getJobType('');
			$heighesteducation = $this->getHeighestEducation('');
			$job_categories = $this->getCategories('');
			$job_salaryrange = $this->getJobSalaryRange('');
			$countries = $this->getCountries('');

			if(isset($this->_application))$address_states = $this->getStates($this->_application->address_country, '');
			if(isset($this->_application))$address_counties = $this->getCounties($this->_application->address_state, '');
			if(isset($this->_application))$address_cities = $this->getCities($this->_application->address_county, '');

			if(isset($this->_application))$institute_states = $this->getStates($this->_application->institute_country, '');
			if(isset($this->_application))$institute_counties = $this->getCounties($this->_application->institute_state, '');
			if(isset($this->_application))$institute_cities = $this->getCities($this->_application->institute_county, '');
			
			if(isset($this->_application))$institute1_states = $this->getStates($this->_application->institute1_country, '');
			if(isset($this->_application))$institute1_counties = $this->getCounties($this->_application->institute1_state, '');
			if(isset($this->_application))$institute1_cities = $this->getCities($this->_application->institute1_county, '');

			if(isset($this->_application))$employer_states = $this->getStates($this->_application->employer_country, '');
			if(isset($this->_application))$employer_counties = $this->getCounties($this->_application->employer_state, '');
			if(isset($this->_application))$employer_cities = $this->getCities($this->_application->employer_county, '');
			
			if ( isset($this->_application) )
			{
				$this->_empoptions['nationality'] = JHTML::_('select.genericList', $countries, 'nationality','class="inputbox" '.'', 'value', 'text', $this->_application->nationality);
				$this->_empoptions['gender'] = JHTML::_('select.genericList', $gender, 'gender','class="inputbox" '.'', 'value', 'text', $this->_application->gender);

				$this->_empoptions['job_category'] = JHTML::_('select.genericList', $job_categories, 'job_category', 'class="inputbox" '. '', 'value', 'text', $this->_application->job_category);

				$this->_empoptions['address_country'] = JHTML::_('select.genericList', $countries, 'address_country','class="inputbox" '.'onChange="dochange(\'address_state\', \'address_county\',\'address_city\', \'state\', this.value)"', 'value', 'text', $this->_application->address_country);
				if (isset($address_states[1])) if ($address_states[1] != '')$this->_empoptions['address_state'] = JHTML::_('select.genericList', $address_states, 'address_state', 'class="inputbox" '. 'onChange="dochange(\'address_county\, \'address_city\', , this.value)"', 'value', 'text', $this->_application->address_state);
				if (isset($address_counties[1])) if ($address_counties[1] != '')$this->_empoptions['address_county'] = JHTML::_('select.genericList', $address_counties, 'address_county', 'class="inputbox" '. 'onChange="dochange(\'address_city\, , , this.value)"', 'value', 'text', $this->_application->address_county);
				if (isset($address_cities[1])) if ($address_cities[1] != '')$this->_empoptions['address_city'] = JHTML::_('select.genericList', $address_cities, 'address_city', 'class="inputbox" '. '', 'value', 'text', $this->_application->address_city);
				
				$this->_empoptions['address1_country'] = JHTML::_('select.genericList', $countries, 'address1_country','class="inputbox" '.'onChange="dochange(\'address1_state\', \'address1_county\',\'address1_city\',\'state\', this.value)"', 'value', 'text', $this->_application->address1_country);
				$this->_empoptions['address2_country'] = JHTML::_('select.genericList', $countries, 'address2_country','class="inputbox" '.'onChange="dochange(\'address2_state\', \'address2_county\',\'address2_city\',\'state\', this.value)"', 'value', 'text', $this->_application->address2_country);

				$this->_empoptions['institute_country'] = JHTML::_('select.genericList', $countries, 'institute_country','class="inputbox" '.'onChange="dochange(\'institute_state\', \'institute_county\',\'institute_city\', \'state\', this.value)"', 'value', 'text', $this->_application->institute_country);
				if (isset($institute_states[1])) if ($institute_states[1] != '')$this->_empoptions['institute_state'] = JHTML::_('select.genericList', $institute_states, 'institute_state', 'class="inputbox" '. 'onChange="dochange(\'institute_county\, \'institute_city\', , this.value)"', 'value', 'text', $this->_application->institute_state);
				if (isset($institute_counties[1])) if ($institute_counties[1] != '')$this->_empoptions['institute_county'] = JHTML::_('select.genericList', $institute_counties, 'institute_county', 'class="inputbox" '. 'onChange="dochange(\'institute_city\,  , , this.value)"', 'value', 'text', $this->_application->institute_county);
				if (isset($institute_cities[1])) if ($institute_cities[1] != '')$this->_empoptions['institute_city'] = JHTML::_('select.genericList', $institute_cities, 'institute_city', 'class="inputbox" '. '', 'value', 'text', $this->_application->institute_city);

				$this->_empoptions['institute1_country'] = JHTML::_('select.genericList', $countries, 'institute1_country','class="inputbox" '.'onChange="dochange(\'institute1_state\', \'institute1_county\',\'institute1_city\',\'state\', this.value)"', 'value', 'text', $this->_application->institute1_country);
				if (isset($institute1_states[1])) if ($institute1_states[1] != '')$this->_empoptions['institute1_state'] = JHTML::_('select.genericList', $institute1_states, 'institute1_state', 'class="inputbox" '. 'onChange="dochange(\'institute1_county\, \'institute1_city\', , this.value)"', 'value', 'text', $this->_application->institute1_state);
				if (isset($institute1_counties[1])) if ($institute1_counties[1] != '')$this->_empoptions['institute1_county'] = JHTML::_('select.genericList', $institute1_counties, 'institute1_county', 'class="inputbox" '. 'onChange="dochange(\'institute1_city\,  , , this.value)"', 'value', 'text', $this->_application->institute1_county);
				if (isset($institute1_cities[1])) if ($institute1_cities[1] != '')$this->_empoptions['institute1_city'] = JHTML::_('select.genericList', $institute1_cities, 'institute1_city', 'class="inputbox" '. '', 'value', 'text', $this->_application->institute1_city);

				$this->_empoptions['institute2_country'] = JHTML::_('select.genericList', $countries, 'institute2_country','class="inputbox" '.'onChange="dochange(\'institute2_state\', \'institute2_county\',\'institute2_city\',\'state\', this.value)"', 'value', 'text', $this->_application->institute2_country);
				$this->_empoptions['institute3_country'] = JHTML::_('select.genericList', $countries, 'institute3_country','class="inputbox" '.'onChange="dochange(\'institute3_state\', \'institute3_county\',\'institute3_city\',\'state\', this.value)"', 'value', 'text', $this->_application->institute3_country);

				$this->_empoptions['employer_country'] = JHTML::_('select.genericList', $countries, 'employer_country','class="inputbox" '.'onChange="dochange(\'employer_state\', \'employer_county\',\'employer_city\',\'state\', this.value)"', 'value', 'text', $this->_application->employer_country);
				if (isset($employer_states[1])) if ($employer_states[1] != '')$this->_empoptions['employer_state'] = JHTML::_('select.genericList', $employer_states, 'employer_state', 'class="inputbox" '. 'onChange="dochange(\'employer_county\, \'employer_city\', , this.value)"', 'value', 'text', $this->_application->employer_state);
				if (isset($employer_counties[1])) if ($employer_counties[1] != '')$this->_empoptions['employer_county'] = JHTML::_('select.genericList', $employer_counties, 'employer_county', 'class="inputbox" '. 'onChange="dochange(\'employer_city\,  , , this.value)"', 'value', 'text', $this->_application->employer_county);
				if (isset($employer_cities[1])) if ($employer_cities[1] != '')$this->_empoptions['employer_city'] = JHTML::_('select.genericList', $employer_cities, 'employer_city', 'class="inputbox" '. '', 'value', 'text', $this->_application->employer_city);

				$this->_empoptions['employer1_country'] = JHTML::_('select.genericList', $countries, 'employer1_country','class="inputbox" '.'onChange="dochange(\'employer1_state\', \'employer1_county\',\'employer1_city\',\'state\', this.value)"', 'value', 'text', $this->_application->employer1_country);
				$this->_empoptions['employer2_country'] = JHTML::_('select.genericList', $countries, 'employer2_country','class="inputbox" '.'onChange="dochange(\'employer2_state\', \'employer2_county\',\'employer2_city\',\'state\', this.value)"', 'value', 'text', $this->_application->employer2_country);
				$this->_empoptions['employer3_country'] = JHTML::_('select.genericList', $countries, 'employer3_country','class="inputbox" '.'onChange="dochange(\'employer3_state\', \'employer3_county\',\'employer3_city\',\'state\', this.value)"', 'value', 'text', $this->_application->employer3_country);

				$this->_empoptions['reference_country'] = JHTML::_('select.genericList', $countries, 'reference_country','class="inputbox" '.'onChange="dochange(\'reference_state\', \'reference_county\',\'reference_city\',\'state\', this.value)"', 'value', 'text', $this->_application->reference_country);
				$this->_empoptions['reference1_country'] = JHTML::_('select.genericList', $countries, 'reference1_country','class="inputbox" '.'onChange="dochange(\'reference1_state\', \'reference1_county\',\'reference1_city\',\'state\', this.value)"', 'value', 'text', $this->_application->reference1_country);
				$this->_empoptions['reference2_country'] = JHTML::_('select.genericList', $countries, 'reference2_country','class="inputbox" '.'onChange="dochange(\'reference2_state\', \'reference2_county\',\'reference2_city\',\'state\', this.value)"', 'value', 'text', $this->_application->reference2_country);
				$this->_empoptions['reference3_country'] = JHTML::_('select.genericList', $countries, 'reference3_country','class="inputbox" '.'onChange="dochange(\'reference3_state\', \'reference3_county\',\'reference3_city\',\'state\', this.value)"', 'value', 'text', $this->_application->reference3_country);

				$this->_empoptions['jobtype'] = JHTML::_('select.genericList', $job_type, 'jobtype', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobtype);
				$this->_empoptions['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', $this->_application->heighestfinisheducation);
				$this->_empoptions['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobsalaryrange);
				$this->_empoptions['currencyid'] = JHTML::_('select.genericList', $this->getCurrency(), 'currencyid', 'class="inputbox" '. '', 'value', 'text', $this->_application->currencyid);


			}
			else
			{
				$this->_empoptions['nationality'] = JHTML::_('select.genericList', $countries, 'nationality','class="inputbox" '.'', 'value', 'text', '');
				$this->_empoptions['gender'] = JHTML::_('select.genericList', $gender, 'gender','class="inputbox" '.'', 'value', 'text', '');

				$this->_empoptions['job_category'] = JHTML::_('select.genericList', $job_categories, 'job_category', 'class="inputbox" '. '', 'value', 'text', '');
				
				$this->_empoptions['address_country'] = JHTML::_('select.genericList', $countries, 'address_country','class="inputbox" '.'onChange="dochange(\'address_state\', \'address_county\',\'address_city\', \'state\', this.value)"', 'value', 'text', '');
				//echo '<br> st '.$address_states[1];
				if ( isset($address_states[1]) )if ($address_states[1] != '')$this->_empoptions['address_state'] = JHTML::_('select.genericList', $address_states, 'address_state', 'class="inputbox" '. 'onChange="dochange(\'address_county\, \'address_city\', , this.value)"', 'value', 'text', '');
				if ( isset($address_counties[1]) )if ($address_counties[1] != '')$this->_empoptions['address_county'] = JHTML::_('select.genericList', $address_counties, 'address_county', 'class="inputbox" '. 'onChange="dochange(\'address_city\, , , this.value)"', 'value', 'text', '');
				if ( isset($address_cities[1]) )if ($address_cities[1] != '')$this->_empoptions['address_city'] = JHTML::_('select.genericList', $address_cities, 'address_city', 'class="inputbox" '. '', 'value', 'text', '');
				
				$this->_empoptions['address1_country'] = JHTML::_('select.genericList', $countries, 'address1_country','class="inputbox" '.'onChange="dochange(\'address1_state\', \'address1_county\',\'address1_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['address2_country'] = JHTML::_('select.genericList', $countries, 'address2_country','class="inputbox" '.'onChange="dochange(\'address2_state\', \'address2_county\',\'address2_city\',\'state\', this.value)"', 'value', 'text', '');

				$this->_empoptions['institute_country'] = JHTML::_('select.genericList', $countries, 'institute_country','class="inputbox" '.'onChange="dochange(\'institute_state\', \'institute_county\',\'institute_city\', \'state\', this.value)"', 'value', 'text', '');
				if ( isset($institute_states[1]) )if ($institute_states[1] != '')$this->_empoptions['institute_state'] = JHTML::_('select.genericList', $institute_states, 'institute_state', 'class="inputbox" '. 'onChange="dochange(\'institute_county\, \'institute_city\', , this.value)"', 'value', 'text', '');
				if ( isset($institute_counties[1]) )if ($institute_counties[1] != '')$this->_empoptions['institute_county'] = JHTML::_('select.genericList', $institute_counties, 'institute_county', 'class="inputbox" '. 'onChange="dochange(\'institute_city\,  , , this.value)"', 'value', 'text', '');
				if ( isset($institute_cities[1]) )if ($institute_cities[1] != '')$this->_empoptions['institute_city'] = JHTML::_('select.genericList', $institute_cities, 'institute_city', 'class="inputbox" '. '', 'value', 'text', '');

				$this->_empoptions['institute1_country'] = JHTML::_('select.genericList', $countries, 'institute1_country','class="inputbox" '.'onChange="dochange(\'institute1_state\', \'institute1_county\',\'institute1_city\',\'state\', this.value)"', 'value', 'text', '');
				if (isset($institute1_states[1])) if ($institute1_states[1] != '')$this->_empoptions['institute1_state'] = JHTML::_('select.genericList', $institute1_states, 'institute1_state', 'class="inputbox" '. 'onChange="dochange(\'institute1_county\, \'institute1_city\', , this.value)"', 'value', 'text', '');
				if (isset($institute1_counties[1])) if ($institute1_counties[1] != '')$this->_empoptions['institute1_county'] = JHTML::_('select.genericList', $institute1_counties, 'institute1_county', 'class="inputbox" '. 'onChange="dochange(\'institute1_city\,  , , this.value)"', 'value', 'text', '');
				if (isset($institute1_cities[1])) if ($institute1_cities[1] != '')$this->_empoptions['institute1_city'] = JHTML::_('select.genericList', $institute1_cities, 'institute1_city', 'class="inputbox" '. '', 'value', 'text', '');

				$this->_empoptions['institute2_country'] = JHTML::_('select.genericList', $countries, 'institute2_country','class="inputbox" '.'onChange="dochange(\'institute2_state\', \'institute2_county\',\'institute2_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['institute3_country'] = JHTML::_('select.genericList', $countries, 'institute3_country','class="inputbox" '.'onChange="dochange(\'institute3_state\', \'institute3_county\',\'institute3_city\',\'state\', this.value)"', 'value', 'text', '');

				$this->_empoptions['employer_country'] = JHTML::_('select.genericList', $countries, 'employer_country','class="inputbox" '.'onChange="dochange(\'employer_state\', \'employer_county\',\'employer_city\',\'state\', this.value)"', 'value', 'text', '');
				if ( isset($employer_states[1]) )if ($employer_states[1] != '')$this->_empoptions['employer_state'] = JHTML::_('select.genericList', $employer_states, 'employer_state', 'class="inputbox" '. 'onChange="dochange(\'employer_county\, \'employer_city\', , this.value)"', 'value', 'text', '');
				if ( isset($employer_counties[1]) )if ($employer_counties[1] != '')$this->_empoptions['employer_county'] = JHTML::_('select.genericList', $employer_counties, 'employer_county', 'class="inputbox" '. 'onChange="dochange(\'employer_city\,  , , this.value)"', 'value', 'text', '');
				if ( isset($employer_cities[1]) )if ($employer_cities[1] != '')$this->_empoptions['employer_city'] = JHTML::_('select.genericList', $employer_cities, 'employer_city', 'class="inputbox" '. '', 'value', 'text', '');

				$this->_empoptions['employer1_country'] = JHTML::_('select.genericList', $countries, 'employer1_country','class="inputbox" '.'onChange="dochange(\'employer1_state\', \'employer1_county\',\'employer1_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['employer2_country'] = JHTML::_('select.genericList', $countries, 'employer2_country','class="inputbox" '.'onChange="dochange(\'employer2_state\', \'employer2_county\',\'employer2_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['employer3_country'] = JHTML::_('select.genericList', $countries, 'employer3_country','class="inputbox" '.'onChange="dochange(\'employer3_state\', \'employer3_county\',\'employer3_city\',\'state\', this.value)"', 'value', 'text', '');

				$this->_empoptions['reference_country'] = JHTML::_('select.genericList', $countries, 'reference_country','class="inputbox" '.'onChange="dochange(\'reference_state\', \'reference_county\',\'reference_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['reference1_country'] = JHTML::_('select.genericList', $countries, 'reference1_country','class="inputbox" '.'onChange="dochange(\'reference1_state\', \'reference1_county\',\'reference1_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['reference2_country'] = JHTML::_('select.genericList', $countries, 'reference2_country','class="inputbox" '.'onChange="dochange(\'reference2_state\', \'reference2_county\',\'reference2_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['reference3_country'] = JHTML::_('select.genericList', $countries, 'reference3_country','class="inputbox" '.'onChange="dochange(\'reference3_state\', \'reference3_county\',\'reference3_city\',\'state\', this.value)"', 'value', 'text', '');


				$this->_empoptions['jobtype'] = JHTML::_('select.genericList', $job_type, 'jobtype', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_empoptions['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_empoptions['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_empoptions['currencyid'] = JHTML::_('select.genericList', $this->getCurrency(), 'currencyid', 'class="inputbox" '. '', 'value', 'text', '');

			}
		}
		return $this->_empoptions;
	}	
	

	function &getSearchOptions($uid)
	{
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$db = &$this->getDBO();

                if($uid == 0){ //guest
                    $canview=1;
                }else{
                    $query = "SELECT package.jobsearch, package.packageexpireindays, payment.created
                    FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." AS package
                    JOIN ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS payment ON payment.packageid = package.id
                    WHERE payment.uid = ".$uid."
                    AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
                    AND payment.transactionverified = 1 AND payment.status = 1";
                    //echo $query;
                    $db->setQuery($query);
                    $jobs = $db->loadObjectList();
                    $canview = 0;
                    if(empty($jobs)) $canview = 1; // for those who not get any role

                    foreach($jobs AS $job){
                            if ($job->jobsearch == 1){
                                       $canview = 1;
                                       break;
                            }else{
                                     $canview = 0;
                            }
                    }
                }
		//echo $query,$canview;
		if($canview == 1){
                    $searchjobconfig = $this->getConfigByFor('searchjob');
		
                    if ( !$this->_searchoptions ){
                            $this->_searchoptions = array();

                            $companies = $this->getAllCompanies(JText::_('JS_SEARCH_ALL'));
                            $job_type = $this->getJobType(JText::_('JS_SEARCH_ALL'));
                            $jobstatus = $this->getJobStatus(JText::_('JS_SEARCH_ALL'));
                            $heighesteducation = $this->getHeighestEducation(JText::_('JS_SEARCH_ALL'));
                            $job_categories = $this->getCategories(JText::_('JS_SEARCH_ALL'));
                            $job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SEARCH_ALL'));
                            $shift = $this->getShift(JText::_('JS_SEARCH_ALL'));
							$countries = $this->getCountries('');
							if(! isset($this->_config)){ $this->getConfig('');}	
							if(isset($this->_defaultcountry))$states = $this->getStates($this->_defaultcountry, '');
							$this->_searchoptions['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_defaultcountry);
							if ( isset($states[1]) ) if ($states[1] != '')$this->_searchoptions['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', '');
							if ( isset($counties[1]) ) if ($counties[1] != '')$this->_searchoptions['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', '');
							if ( isset($cities[1]) ) if ($cities[1] != '')$this->_searchoptions['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', '');

							
							
                            $lists['heighesteducation'] = JHTML::_('select.genericList', $this->getHeighestEducation(''), 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', '');
                            $lists['shift'] = JHTML::_('select.genericList', $this->getShift(''), 'shift', 'class="inputbox" '. '', 'value', 'text', '');

                            $this->_searchoptions['educationminimax'] = JHTML::_('select.genericList', $this->getMiniMax(''), 'educationminimax', 'class="inputbox" '. '', 'value', 'text', '');
                            $this->_searchoptions['education'] = JHTML::_('select.genericList', $this->getHeighestEducation(''), 'educationid', 'class="inputbox" '. '', 'value', 'text', '');
                            $lists['minimumeducationrange'] = JHTML::_('select.genericList', $this->getHeighestEducation(JText::_('JS_MINIMUM')), 'mineducationrange', 'class="inputbox" '. '', 'value', 'text', '');
                            $lists['maximumeducationrange'] = JHTML::_('select.genericList', $this->getHeighestEducation(JText::_('JS_MAXIMUM')), 'maxeducationrange', 'class="inputbox" '. '', 'value', 'text', '');

                            $this->_searchoptions['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', '');
                            $this->_searchoptions['salaryrangefrom'] = JHTML::_('select.genericList', $this->getJobSalaryRange(JText::_('JS_FROM')), 'salaryrangefrom', 'class="inputbox" '. '', 'value', 'text', '');
                            $this->_searchoptions['salaryrangeto'] = JHTML::_('select.genericList', $this->getJobSalaryRange(JText::_('JS_TO')), 'salaryrangeto', 'class="inputbox" '. '', 'value', 'text', '');
                            $this->_searchoptions['salaryrangetypes'] = JHTML::_('select.genericList', $this->getSalaryRangeTypes(''), 'salaryrangetype', 'class="inputbox" '. '', 'value', 'text', 2);
                            
                            $this->_searchoptions['companies'] = JHTML::_('select.genericList', $companies, 'company', 'class="inputbox" '. '', 'value', 'text', '');
                            $this->_searchoptions['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'jobcategory', 'class="inputbox" '. '', 'value', 'text', '');
                            $this->_searchoptions['jobstatus'] = JHTML::_('select.genericList', $jobstatus, 'jobstatus', 'class="inputbox" '. '', 'value', 'text', '');
                            $this->_searchoptions['jobtype'] = JHTML::_('select.genericList', $job_type, 'jobtype', 'class="inputbox" '. '', 'value', 'text', '');
                            $this->_searchoptions['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', '');
                            $this->_searchoptions['shift'] = JHTML::_('select.genericList', $shift, 'shift', 'class="inputbox" '. '', 'value', 'text', '');
                            $this->_searchoptions['currency'] = JHTML::_('select.genericList', $this->getCurrency(), 'currency', 'class="inputbox" '. '', 'value', 'text', '');
                    }
                    $result = array();
                    $result[0] = $this->_searchoptions;
                    $result[1] = $searchjobconfig;
                    $result[2]= $canview;

		}else{
			$result[2]= $canview;
		}
		return $result;
	}	
	
	function &getResumeSearchOptions($uid)
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
                $db = &$this->getDBO();

                $query = "SELECT package.resumesearch, package.packageexpireindays, payment.created
		FROM ".$db->nameQuote('#__wrecruit_employerpackages')." AS package
		JOIN ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS payment ON payment.packageid = package.id
		WHERE payment.uid = ".$uid."
		AND DATE_ADD(payment.created,INTERVAL package.packageexpireindays DAY) >= CURDATE()
		AND payment.transactionverified = 1 AND payment.status = 1";
//		echo $query;
		$db->setQuery($query);
		$jobs = $db->loadObjectList();
		//$unlimited = 0;
                 $canview = 0;
		foreach($jobs AS $job){
			if ($job->resumesearch == 1){
				   $canview = 1; 
				   break;
			}else{
				 $canview = 0;
			}
		}
		if($canview==1){

			$searchresumeconfig = $this->getConfigByFor('searchresume');

			$gender = array(
			'0' => array('value' => '','text' => JText::_('JS_SEARCH_ALL')),
			'1' => array('value' => 1,'text' => JText::_('JS_MALE')),
			'2' => array('value' => 2,'text' => JText::_('JS_FEMALE')),);

			$nationality = $this->getCountries(JText::_('JS_SEARCH_ALL'));
			$job_type = $this->getJobType(JText::_('JS_SEARCH_ALL'));
			$heighesteducation = $this->getHeighestEducation(JText::_('JS_SEARCH_ALL'));			
			$job_categories = $this->getCategories("");
			$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SEARCH_ALL'));
			
//			print_r($job_categories);
//			$searchoptions['jobcategory']Utilities::selectListMulti('jobcategory', 'jobcategory', $job_categories, "", "", "value", "text", "inputbox", "");			
			$searchoptions['nationality'] = JHTML::_('select.genericList', $nationality, 'nationality', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'jobcategory[]', 'class="inputbox" multiple="multiple" '. '', 'value', 'text', '');
			$searchoptions['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['jobtype'] = JHTML::_('select.genericList', $job_type, 'jobtype', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['gender'] = JHTML::_('select.genericList', $gender, 'gender', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['currency'] = JHTML::_('select.genericList', $this->getCurrency(), 'currency', 'class="inputbox" '. '', 'value', 'text', '');
			$result=array();
			$result[0]=$searchoptions;
			
			$result[1]=$searchresumeconfig;
			$result[2]= $canview;
			}else{
			$result[2]= $canview;
			}
		return $result;
	}	
	
	function &getOptions()
	{
		if ( !$this->_options )
		{
			$this->_options = array();
							
			$jobtype = $this->getJobType('');
			$jobstatus = $this->getJobStatus('');
			$heighesteducation = $this->getHeighestEducation('');
		
			$job_categories = $this->getCategories('');
			$job_salaryrange = $this->getJobSalaryRange('');
			$countries = $this->getCountries('');
			if ( isset($this->_application) ){
				$states = $this->getStates($this->_application->country, '');
				$counties = $this->getCounties($this->_application->state, '');
				$cities = $this->getCities($this->_application->county, '');
			}

			if ( isset($this->_application) )
			{
				$this->_options['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'jobcategory', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobcategory);
				$this->_options['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobsalaryrange);
				$this->_options['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_application->country);
				if ( isset($states[1]) ) if ($states[1] != '')$this->_options['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', $this->_application->state);
				if ( isset($counties[1]) ) if ($counties[1] != '')$this->_options['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', $this->_application->county);
				if ( isset($cities[1]) ) if ($cities[1] != '')$this->_options['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', $this->_application->city);
				$this->_options['jobstatus'] = JHTML::_('select.genericList', $jobstatus, 'jobstatus', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobstatus);
				$this->_options['jobtype'] = JHTML::_('select.genericList', $jobtype, 'jobtype', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobtype);
				$this->_options['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', $this->_application->heighestfinisheducation);

			}
			else
			{
				$this->_options['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'jobcategory', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_options['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_options['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', '');
				if ( isset($states[1]) ) if ($states[1] != '')$this->_options['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', '');
				if ( isset($counties[1]) ) if ($counties[1] != '')$this->_options['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', '');
				if ( isset($cities[1]) ) if ($cities[1] != '')$this->_options['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_options['jobstatus'] = JHTML::_('select.genericList', $jobstatus, 'jobstatus', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_options['jobtype'] = JHTML::_('select.genericList', $jobtype, 'jobtype', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_options['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', '');
				
			}
		}
		return $this->_options;
	}	
	
	function &getFilterLists()
	{
		//if ( !$this->_filterlists ){
			$this->_filterlists = array();

			$jobtype = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
		//	$jobtype = $this->getJobType('abc');
			$jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));
			$heighesteducation = $this->getHeighestEducation(JText::_('JS_SELECT_EDUCATION'));

			$job_categories = $this->getCategories(JText::_('JS_SELECT_CATEGORY'));
			$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SELECT_SALARY'));
			$countries = $this->getCountries('');
			
			//$this->_filterlists['country'] = JHTML::_('select.genericList', $countries, 'cmbfilter_country','class="inputbox" '.'onChange="dochange(\'filter_state\', \'filter_county\',\'filter_city\',\'state\', this.value)"', 'value', 'text', '');
			$this->_filterlists['country'] = JHTML::_('select.genericList', $countries, 'cmbfilter_country','class="inputbox" '.'onChange="dochange(\'filter_state\', this.value)"', 'value', 'text', '');

			$this->_filterlists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'filter_jobcategory', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_filterlists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'filter_jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_filterlists['jobtype'] = JHTML::_('select.genericList', $jobtype, 'filter_jobtype', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_filterlists['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'filter_heighesteducation', 'class="inputbox" '. '', 'value', 'text', '');
				
		//}
		return $this->_filterlists;
	}	
	

	function getCategories( $title )
	{
		$db =& JFactory::getDBO();
		
		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_categories')." WHERE isactive = 1 ORDER BY cat_title ";
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$jobcategories = array();
		if($title)
			$jobcategories[] =  array('value' => JText::_(''),'text' => $title);
			
		foreach($rows as $row)
		{
			$jobcategories[] =  array('value' => $row->id,
								'text' => JText::_($row->cat_title));
		}
		return $jobcategories;	
			
	}

	function getSubCategoriesforCombo($categoryid, $title, $value  ){
		$db =& JFactory::getDBO();

		$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_subcategories')." WHERE status = 1 AND categoryid = ".$categoryid." ORDER BY title ";
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$subcategories = array();
		if ($title) $subcategories[] =  array('value' => JText::_($value),	'text' => JText::_($title));
                foreach($rows as $row){
                    $subcategories[] =  array('value' => $row->id, 'text' => JText::_($row->title));
		}
		return $subcategories;
	}
	function &getCurU()
	{
		$result = array();
		$result[0] = 'a'.substr($this->_arv,16,2).substr($this->_arv,24,1);
		$result[1] = substr($this->_arv,5,2).substr($this->_arv,12,3).substr($this->_arv,20,1).'e';
		$result[2] = $_SERVER['SERVER_NAME'];
		return $result;
	}

/*        function getJobSalaryRange( $title )
	{
		$db =& JFactory::getDBO();
		if ( !$this->_jobsalaryrange ){		
			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_salaryrange')." ORDER BY 'id' ";
			//echo '<br>sql '.$query;
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_jobsalaryrange = $rows;
		}
		
		if ( !$this->_config )
			$this->getConfig('');
		foreach ($this->_config as $conf){
			if ($conf->configname == 'currency')
				$currency = $conf->configvalue;
		}

		$jobsalaryrange = array();
		if($title)
			$jobsalaryrange[] =  array('value' => JText::_(''),'text' => $title);

		foreach($this->_jobsalaryrange as $row)
		{
			$salrange = $currency . $row->rangestart.' - '.$currency . $row->rangeend;
			$salrange = $currency . $row->rangestart;//.' - '.$currency . $row->rangeend;
			$jobsalaryrange[] =  array('value' => $row->id,	'text' => $salrange);
		}
		return $jobsalaryrange;	
			
	}
	*/

        function getJobSalaryRange( $title )
	{
		$db =& JFactory::getDBO();
		if ( !$this->_jobsalaryrange ){		
			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_salaryrange')." ORDER BY 'id' ";
			//echo '<br>sql '.$query;
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_jobsalaryrange = $rows;
		}
		/*
		if ( !$this->_config )
			$this->getConfig('');
		foreach ($this->_config as $conf){
			if ($conf->configname == 'currency')
				$currency = $conf->configvalue;
		}*/
		//echo $currency; die();
		$jobsalaryrange = array();
		if($title)
			$jobsalaryrange[] =  array('value' => JText::_(''),'text' => $title);

		foreach($this->_jobsalaryrange as $row)
		{
			$salrange = $row->rangestart.' - '. $row->rangeend;
			$salrange = $row->rangestart;//.' - '.$currency . $row->rangeend;
			$jobsalaryrange[] =  array('value' => $row->id,	'text' => $salrange);
		}
		return $jobsalaryrange;	
			
	}



/**sce */
	function jobTypes($id, $val, $fild ){
		if (is_numeric($val) == false) return false;
		if ( !$this->_config )
			$this->getConfig('');
			
			foreach ($this->_config as $conf){
				if ($conf->configname == $fild)
					$value = $conf->configvalue;
			}
		$value = $this->getSubVal($value);
		if ($value != $id ) return 3;
		$db =& JFactory::getDBO();
		$query = "UPDATE ".$db->nameQuote('#__wrecruit_jobtypes')." SET status = ".$val;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;	
	}
	function jobShifts($id, $val, $fild ){
		if (is_numeric($val) == false) return false;
		if ( !$this->_config )
			$this->getConfig('');
			foreach ($this->_config as $conf){
				if ($conf->configname == $fild)
					$value = $conf->configvalue;
			}
		if ($value != $id ) return 3;
		$db =& JFactory::getDBO();
		$query = "UPDATE ".$db->nameQuote('#__wrecruit_shifts')." SET status = ".$val;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;	
	}


	function getCountries( $title )
	{
		if ( !$this->_countries ){
			$db =& JFactory::getDBO();
			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_countries')." WHERE enabled = 'Y' ORDER BY name ASC ";
			//echo '<br>sql '.$query;
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_countries = $rows;
		}
		$countries = array();
		if($title)
			$countries[] =  array('value' => JText::_(''),'text' => $title);
		else	
			$countries[] =  array('value' => JText::_(''),'text' => JText::_('JS_CHOOSE_COUNTRY'));
		
		foreach($this->_countries as $row)	{
			$countries[] =  array('value' => $row->code,'text' => JText::_($row->name));
		}
		return $countries;	
	}

	function getStates( $countrycode, $title)
	{
		$db =& JFactory::getDBO();
		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_states')." WHERE enabled = 'Y' AND countrycode = '". $countrycode ."' ORDER BY name ASC ";
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$states = array();
		if($title)
			$states[] =  array('value' => JText::_(''),'text' => $title);
		else	
			$states[] =  array('value' => JText::_(''),	'text' => JText::_('JS_CHOOSE_STATE'));
			
		foreach($rows as $row)
		{
			$states[] =  array('value' => JText::_($row->code),
							'text' => JText::_($row->name));
		}
		return $states;	
	}
	function getCounties( $statecode, $title )

	{
		$db =& JFactory::getDBO();
		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_counties')." WHERE enabled = 'Y' AND statecode = '". $statecode ."' ORDER BY name ASC ";
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$counties = array();
		if($title)
			$counties[] =  array('value' => JText::_(''),'text' => $title);
		else	
			$counties[] =  array('value' => JText::_(''),	'text' => JText::_('JS_CHOOSE_COUNTY'));
			
		foreach($rows as $row)
		{
			$counties[] =  array('value' => JText::_($row->code),
							'text' => JText::_($row->name));
		}
		return $counties;	
	}
	function getCities( $countycode, $title )
	{
		$db =& JFactory::getDBO();
		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_cities')." WHERE enabled = 'Y' AND countycode = '". $countycode ."' ORDER BY name ASC ";
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$cities = array();
		if($title)
			$cities[] =  array('value' => JText::_(''),'text' => $title);
		else	
			$cities[] =  array('value' => JText::_(''),	'text' => JText::_('JS_CHOOSE_CITY'));
			
		foreach($rows as $row)
		{
			$cities[] =  array('value' => JText::_($row->code),
							'text' => JText::_($row->name));
		}
		return $cities;	
	}

	function getCompanies( $uid )
	{
			if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
			$db =& JFactory::getDBO();
			$query = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_companies')." WHERE uid = ". $uid ." AND status = 1 ORDER BY name ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$companies = array();
			foreach($rows as $row)
			{
				$companies[] =  array('value' => $row->id,'text' => $row->name);
			}
		return $companies;	
	}
	
	function getAllCompanies( $title )
	{
            $db =& JFactory::getDBO();
            $query = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_companies')." ORDER BY name ASC ";
            $db->setQuery( $query );
            $rows = $db->loadObjectList();
            if ($db->getErrorNum()) {
                    echo $db->stderr();
                    return false;
            }
            $companies = array();
            if($title)
                    $companies[] =  array('value' => JText::_(''),'text' => $title);
            foreach($rows as $row){
                    $companies[] =  array('value' => $row->id,'text' => $row->name);
            }
            return $companies;
	}
	
	function getJobType( $title ){
//		if ( !$this->_jobtype){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_jobtypes')." WHERE isactive = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_jobtype = array();
			if($title)
				$this->_jobtype[] =  array('value' => JText::_(''),'text' => $title);

			foreach($rows as $row)
			{
				$this->_jobtype[] =  array('value' => $row->id,
								'text' => JText::_($row->title));
			}
		
//		}
		return $this->_jobtype;	
	}

	function getJobStatus( $title ){
//		if ( !$this->_jobstatus){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_jobstatus')." WHERE isactive = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_jobstatus = array();
			if($title)
				$this->_jobstatus[] =  array('value' => JText::_(''),'text' => $title);

			foreach($rows as $row)	{
				$this->_jobstatus[] =  array('value' => $row->id,	'text' => JText::_($row->title));
			}
//		}
		return $this->_jobstatus;	
	}

	function getHeighestEducation( $title ){
		if ( !$this->_heighesteducation ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_heighesteducation')." WHERE isactive = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_heighesteducation = $rows;
		}						
			$heighesteducation = array();
			if($title)
				$heighesteducation[] =  array('value' => JText::_(''),'text' => $title);

			foreach($this->_heighesteducation as $row)	{
				$heighesteducation[] =  array('value' =>$row->id,	'text' => JText::_($row->title));
			}
		return $heighesteducation;	
	}

	function getShift( $title ){
		if ( !$this->_shifts ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_shifts')." WHERE isactive = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_shifts = array();
			if($title)
				$this->_shifts[] =  array('value' => JText::_(''),'text' => $title);
			foreach($rows as $row)	{
				$this->_shifts[] =  array('value' => $row->id,	'text' => JText::_($row->title));
			}
		}						
		return $this->_shifts;	
	}

	function getSalaryRangeTypes( $title ){
		$db =& JFactory::getDBO();
		$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_salaryrangetypes')." WHERE status = 1 ORDER BY id ASC ";
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$types = array();
		if($title)
			$types[] =  array('value' => JText::_(''),'text' => $title);
		foreach($rows as $row)	{
			$types[] =  array('value' => $row->id,	'text' => JText::_($row->title));
		}
		return $types;	
	}
	function getCareerLevels( $title ){
		if ( !$this->_careerlevels ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_careerlevels')." WHERE status = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_careerlevels = array();
			if($title)
				$this->_careerlevels[] =  array('value' => JText::_(''),'text' => $title);
			foreach($rows as $row)	{
				$this->_careerlevels[] =  array('value' => $row->id,	'text' => JText::_($row->title));
			}
		}						
		return $this->_careerlevels;	
	}

	function getAges( $title ){
		if ( !$this->_ages ){// make problem with age from, age to
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_ages')." WHERE status = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_ages = $rows;
		}						
			$ages = array();
			if($title)
				$ages[] =  array('value' => JText::_(''),'text' => $title);
			foreach($this->_ages  as $row)	{
				$ages[] =  array('value' => $row->id,	'text' => JText::_($row->title));
			}
		return $ages;	
	}

	function getMiniMax( $title ){
		$minimax = array();
		if($title)
			$minimax[] =  array('value' => JText::_(''),'text' => $title);
		$minimax[] =  array('value' => 1,'text' => JText::_('JS_MINIMUM'));
		$minimax[] =  array('value' => 2,'text' => JText::_('JS_MAXIMUM'));
		
		return $minimax;	
	}
	
	function getSubVal($value){
		$mdr= ''; $mdrg9=''; $mdrt11='';$val='';		
		for ($i = 0; $i < strlen(substr($value,1,3)); $i++)	$mdr += ord($value[$i]);
		for ($i = 0; $i < strlen(substr($value,7,3)); $i++)	$mdrg9 += ord($value[$i]);
		for ($i = 0; $i < strlen(substr($value,11,3)); $i++)$mdrt11 += ord($value[$i]);
		$val = substr($value,0,3).$mdrg9.substr($value,3,4).$mdrt11.substr($value,6,5).$mdr.substr($value,11,3);
		return $val;
	}
	function getExperiences( $title ){
		if ( !$this->_experiences ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_experiences')." WHERE status = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_experiences = $rows;
		}	
			
			$experiences = array();
			if($title)
				$experiences[] =  array('value' => JText::_(''),'text' => $title);
			foreach($this->_experiences as $row)	{
				$experiences[] =  array('value' => $row->id,	'text' => JText::_($row->title));
			}
		return $experiences;	
	}
	function getCareerLevel( $title ){
		if ( !$this->_careerlevel ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_careerlevels')." WHERE status = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_careerlevel = $rows;
		}	
			
			$careerlevel = array();
			if($title)
				$careerlevel[] =  array('value' => JText::_(''),'text' => $title);
			foreach($this->_careerlevel as $row)	{
				$careerlevel[] =  array('value' => $row->id,	'text' => JText::_($row->title));
			}
		return $careerlevel;	
	}
	function getDepartmentsByCompanyId( $companyid, $title ){
		$db =& JFactory::getDBO();
                $departments = array();
		if ($companyid){
			$query = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_departments')." WHERE status = 1 AND companyid = ".$companyid." ORDER BY name ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
				
			if($title)
				$departments[] =  array('value' => JText::_(''),'text' => $title);
			foreach($rows as $row)	{
				$departments[] =  array('value' => $row->id,	'text' => JText::_($row->name));
			}
		}	
		return $departments;	
	}
	
	function getMyFoldersForCombo( $uid, $title ){
		$db =& JFactory::getDBO();
                $folders = array();
		
                $query = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_folders')." WHERE status = 1 AND uid = ".$uid." ORDER BY name ASC ";

                $db->setQuery( $query );
                $rows = $db->loadObjectList();
                if ($db->getErrorNum()) {
                        echo $db->stderr();
                        return false;
                }

                if($title)
                        $folders[] =  array('value' => JText::_(''),'text' => $title);
                foreach($rows as $row)	{
                        $folders[] =  array('value' => $row->id,'text' => JText::_($row->name));
                }
		return $folders;
	}
	function getRequiredTravel($title){
		$requiredtravel = array();
		if ($title)
			$requiredtravel[] = array('value' => '','text' => $title);
		$requiredtravel[] = array('value' => 1,'text' => JText::_('JS_NOT_REQUIRED'));
		$requiredtravel[] = array('value' => 2,'text' => JText::_('JS_25_PER'));
		$requiredtravel[] = array('value' => 3,'text' => JText::_('JS_50_PER'));
		$requiredtravel[] = array('value' => 4,'text' => JText::_('JS_75_PER'));
		$requiredtravel[] = array('value' => 5,'text' => JText::_('JS_100_PER'));
		return $requiredtravel;
	}
	function getGender($title){
		$gender = array();
		if ($title)
			$gender[] = array('value' => '','text' => $title);
		$gender[] = array('value' => 1,'text' => JText::_('JS_MALE'));
		$gender[] = array('value' => 2,'text' => JText::_('JS_FEMALE'));
		return $gender;
	}
	function getSendEmail(){
		$values = array();
		$values[] = array('value' => 0,'text' => JText::_('JS_NO'));
		$values[] = array('value' => 1,'text' => JText::_('JS_YES'));
		$values[] = array('value' => 2,'text' => JText::_('JS_YES_WITH_RESUME'));
		return $values;
	}
	
	function getExtension($str) {
		 $i = strrpos($str,".");
		 if (!$i) { return ""; }
		 $l = strlen($str) - $i;
		 $ext = substr($str,$i+1,$l);
		 return $ext;
	}


}
?>
